ovs-vsctl: Drop redundant {port,iface}-{set,get}-external-ids commands.
[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 <regex.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "command-line.h"
32 #include "compiler.h"
33 #include "dirs.h"
34 #include "dynamic-string.h"
35 #include "json.h"
36 #include "ovsdb-data.h"
37 #include "ovsdb-idl.h"
38 #include "poll-loop.h"
39 #include "svec.h"
40 #include "vswitchd/vswitch-idl.h"
41 #include "timeval.h"
42 #include "util.h"
43
44 #include "vlog.h"
45 #define THIS_MODULE VLM_vsctl
46
47 /* --db: The database server to contact. */
48 static const char *db;
49
50 /* --oneline: Write each command's output as a single line? */
51 static bool oneline;
52
53 /* --dry-run: Do not commit any changes. */
54 static bool dry_run;
55
56 /* --no-wait: Wait for ovs-vswitchd to reload its configuration? */
57 static bool wait_for_reload = true;
58
59 /* --timeout: Time to wait for a connection to 'db'. */
60 static int timeout = 5;
61
62 static void vsctl_fatal(const char *, ...) PRINTF_FORMAT(1, 2) NO_RETURN;
63 static char *default_db(void);
64 static void usage(void) NO_RETURN;
65 static void parse_options(int argc, char *argv[]);
66
67 static void check_vsctl_command(int argc, char *argv[]);
68 static void do_vsctl(int argc, char *argv[], struct ovsdb_idl *idl);
69
70 int
71 main(int argc, char *argv[])
72 {
73     struct ovsdb_idl *idl;
74     unsigned int seqno;
75     struct ds args;
76     int start, n_commands;
77     int trials;
78     int i;
79
80     set_program_name(argv[0]);
81     signal(SIGPIPE, SIG_IGN);
82     time_init();
83     vlog_init();
84     vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_WARN);
85     vlog_set_levels(VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
86     parse_options(argc, argv);
87
88     if (timeout) {
89         time_alarm(timeout);
90     }
91
92     /* Log our arguments.  This is often valuable for debugging systems. */
93     ds_init(&args);
94     for (i = 1; i < argc; i++) {
95         ds_put_format(&args, " %s", argv[i]);
96     }
97     VLOG_INFO("Called as%s", ds_cstr(&args));
98     ds_destroy(&args);
99
100     /* Do basic command syntax checking. */
101     n_commands = 0;
102     for (start = i = optind; i <= argc; i++) {
103         if (i == argc || !strcmp(argv[i], "--")) {
104             if (i > start) {
105                 check_vsctl_command(i - start, &argv[start]);
106                 n_commands++;
107             }
108             start = i + 1;
109         }
110     }
111     if (!n_commands) {
112         vsctl_fatal("missing command name (use --help for help)");
113     }
114
115     /* Now execute the commands. */
116     idl = ovsdb_idl_create(db, &ovsrec_idl_class);
117     seqno = ovsdb_idl_get_seqno(idl);
118     trials = 0;
119     for (;;) {
120         unsigned int new_seqno;
121
122         ovsdb_idl_run(idl);
123         new_seqno = ovsdb_idl_get_seqno(idl);
124         if (new_seqno != seqno) {
125             if (++trials > 5) {
126                 vsctl_fatal("too many database inconsistency failures");
127             }
128             do_vsctl(argc - optind, argv + optind, idl);
129             seqno = new_seqno;
130         }
131
132         ovsdb_idl_wait(idl);
133         poll_block();
134     }
135 }
136
137 static void
138 vsctl_fatal(const char *format, ...)
139 {
140     char *message;
141     va_list args;
142
143     va_start(args, format);
144     message = xvasprintf(format, args);
145     va_end(args);
146
147     vlog_set_levels(VLM_vsctl, VLF_CONSOLE, VLL_EMER);
148     VLOG_ERR("%s", message);
149     ovs_fatal(0, "%s", message);
150 }
151
152 static void
153 parse_options(int argc, char *argv[])
154 {
155     enum {
156         OPT_DB = UCHAR_MAX + 1,
157         OPT_ONELINE,
158         OPT_NO_SYSLOG,
159         OPT_NO_WAIT,
160         OPT_DRY_RUN,
161         VLOG_OPTION_ENUMS
162     };
163     static struct option long_options[] = {
164         {"db", required_argument, 0, OPT_DB},
165         {"no-syslog", no_argument, 0, OPT_NO_SYSLOG},
166         {"no-wait", no_argument, 0, OPT_NO_WAIT},
167         {"dry-run", no_argument, 0, OPT_DRY_RUN},
168         {"oneline", no_argument, 0, OPT_ONELINE},
169         {"timeout", required_argument, 0, 't'},
170         {"help", no_argument, 0, 'h'},
171         {"version", no_argument, 0, 'V'},
172         VLOG_LONG_OPTIONS,
173         {0, 0, 0, 0},
174     };
175
176
177     for (;;) {
178         int c;
179
180         c = getopt_long(argc, argv, "+v::hVt:", long_options, NULL);
181         if (c == -1) {
182             break;
183         }
184
185         switch (c) {
186         case OPT_DB:
187             db = optarg;
188             break;
189
190         case OPT_ONELINE:
191             oneline = true;
192             break;
193
194         case OPT_NO_SYSLOG:
195             vlog_set_levels(VLM_vsctl, VLF_SYSLOG, VLL_WARN);
196             break;
197
198         case OPT_NO_WAIT:
199             wait_for_reload = false;
200             break;
201
202         case OPT_DRY_RUN:
203             dry_run = true;
204             break;
205
206         case 'h':
207             usage();
208
209         case 'V':
210             OVS_PRINT_VERSION(0, 0);
211             exit(EXIT_SUCCESS);
212
213         case 't':
214             timeout = strtoul(optarg, NULL, 10);
215             if (timeout < 0) {
216                 ovs_fatal(0, "value %s on -t or --timeout is invalid",
217                           optarg);
218             }
219             break;
220
221         VLOG_OPTION_HANDLERS
222
223         case '?':
224             exit(EXIT_FAILURE);
225
226         default:
227             abort();
228         }
229     }
230
231     if (!db) {
232         db = default_db();
233     }
234 }
235
236 static void
237 usage(void)
238 {
239     printf("\
240 %s: ovs-vswitchd management utility\n\
241 usage: %s [OPTIONS] COMMAND [ARG...]\n\
242 \n\
243 Bridge commands:\n\
244   add-br BRIDGE               create a new bridge named BRIDGE\n\
245   add-br BRIDGE PARENT VLAN   create new fake BRIDGE in PARENT on VLAN\n\
246   del-br BRIDGE               delete BRIDGE and all of its ports\n\
247   list-br                     print the names of all the bridges\n\
248   br-exists BRIDGE            test whether BRIDGE exists\n\
249   br-to-vlan BRIDGE           print the VLAN which BRIDGE is on\n\
250   br-to-parent BRIDGE         print the parent of BRIDGE\n\
251   br-set-external-id BRIDGE KEY VALUE  set KEY on BRIDGE to VALUE\n\
252   br-set-external-id BRIDGE KEY  unset KEY on BRIDGE\n\
253   br-get-external-id BRIDGE KEY  print value of KEY on BRIDGE\n\
254   br-get-external-id BRIDGE  list key-value pairs on BRIDGE\n\
255 \n\
256 Port commands:\n\
257   list-ports BRIDGE           print the names of all the ports on BRIDGE\n\
258   add-port BRIDGE PORT        add network device PORT to BRIDGE\n\
259   add-bond BRIDGE PORT IFACE...  add bonded port PORT in BRIDGE from IFACES\n\
260   del-port [BRIDGE] PORT      delete PORT (which may be bonded) from BRIDGE\n\
261   port-to-br PORT             print name of bridge that contains PORT\n\
262 A bond is considered to be a single port.\n\
263 \n\
264 Interface commands (a bond consists of multiple interfaces):\n\
265   list-ifaces BRIDGE          print the names of all interfaces on BRIDGE\n\
266   iface-to-br IFACE           print name of bridge that contains IFACE\n\
267 \n\
268 Controller commands:\n\
269   get-controller [BRIDGE]     print the controller for BRIDGE\n\
270   del-controller [BRIDGE]     delete the controller for BRIDGE\n\
271   set-controller [BRIDGE] TARGET  set the controller for BRIDGE to TARGET\n\
272   get-fail-mode [BRIDGE]      print the fail-mode for BRIDGE\n\
273   del-fail-mode [BRIDGE]      delete the fail-mode for BRIDGE\n\
274   set-fail-mode [BRIDGE] MODE set the fail-mode for BRIDGE to MODE\n\
275 \n\
276 SSL commands:\n\
277   get-ssl                     print the SSL configuration\n\
278   del-ssl                     delete the SSL configuration\n\
279   set-ssl PRIV-KEY CERT CA-CERT  set the SSL configuration\n\
280 \n\
281 Database commands:\n\
282   list TBL [REC]              list RECord (or all records) in TBL\n\
283   get TBL REC COL[:KEY]       print values of COLumns in RECORD in TBL\n\
284   set TBL REC COL[:KEY]=VALUE set COLumn values in RECord in TBL\n\
285   add TBL REC COL [KEY=]VALUE add (KEY=)VALUE to COLumn in RECord in TBL\n\
286   remove TBL REC COL [KEY=]VALUE  remove (KEY=)VALUE from COLumn\n\
287   clear TBL REC COL           clear values from COLumn in RECord in TBL\n\
288   create TBL COL[:KEY]=VALUE  create and initialize new record\n\
289   destroy TBL REC             delete REC from TBL\n\
290 Potentially unsafe database commands require --force option.\n\
291 \n\
292 Options:\n\
293   --db=DATABASE               connect to DATABASE\n\
294                               (default: %s)\n\
295   --oneline                   print exactly one line of output per command\n",
296            program_name, program_name, default_db());
297     vlog_usage();
298     printf("\n\
299 Other options:\n\
300   -h, --help                  display this help message\n\
301   -V, --version               display version information\n");
302     exit(EXIT_SUCCESS);
303 }
304
305 static char *
306 default_db(void)
307 {
308     static char *def;
309     if (!def) {
310         def = xasprintf("unix:%s/ovsdb-server", ovs_rundir);
311     }
312     return def;
313 }
314 \f
315 struct vsctl_context {
316     int argc;
317     char **argv;
318     struct ovsdb_idl *idl;
319     const struct ovsrec_open_vswitch *ovs;
320     struct ds output;
321     struct shash options;
322 };
323
324 struct vsctl_bridge {
325     struct ovsrec_bridge *br_cfg;
326     char *name;
327     struct ovsrec_controller *ctrl;
328     struct vsctl_bridge *parent;
329     int vlan;
330 };
331
332 struct vsctl_port {
333     struct ovsrec_port *port_cfg;
334     struct vsctl_bridge *bridge;
335 };
336
337 struct vsctl_iface {
338     struct ovsrec_interface *iface_cfg;
339     struct vsctl_port *port;
340 };
341
342 struct vsctl_info {
343     struct shash bridges;
344     struct shash ports;
345     struct shash ifaces;
346     struct ovsrec_controller *ctrl;
347 };
348
349 static struct ovsdb_idl_txn *
350 txn_from_openvswitch(const struct ovsrec_open_vswitch *ovs)
351 {
352     return ovsdb_idl_txn_get(&ovs->header_);
353 }
354
355 static struct vsctl_bridge *
356 add_bridge(struct vsctl_info *b,
357            struct ovsrec_bridge *br_cfg, const char *name,
358            struct vsctl_bridge *parent, int vlan)
359 {
360     struct vsctl_bridge *br = xmalloc(sizeof *br);
361     br->br_cfg = br_cfg;
362     br->name = xstrdup(name);
363     br->parent = parent;
364     br->vlan = vlan;
365     br->ctrl = parent ? parent->br_cfg->controller : br_cfg->controller;
366     shash_add(&b->bridges, br->name, br);
367     return br;
368 }
369
370 static bool
371 port_is_fake_bridge(const struct ovsrec_port *port_cfg)
372 {
373     return (port_cfg->fake_bridge
374             && port_cfg->tag
375             && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095);
376 }
377
378 static struct vsctl_bridge *
379 find_vlan_bridge(struct vsctl_info *info,
380                  struct vsctl_bridge *parent, int vlan)
381 {
382     struct shash_node *node;
383
384     SHASH_FOR_EACH (node, &info->bridges) {
385         struct vsctl_bridge *br = node->data;
386         if (br->parent == parent && br->vlan == vlan) {
387             return br;
388         }
389     }
390
391     return NULL;
392 }
393
394 static void
395 free_info(struct vsctl_info *info)
396 {
397     struct shash_node *node;
398
399     SHASH_FOR_EACH (node, &info->bridges) {
400         struct vsctl_bridge *bridge = node->data;
401         free(bridge->name);
402         free(bridge);
403     }
404     shash_destroy(&info->bridges);
405
406     SHASH_FOR_EACH (node, &info->ports) {
407         struct vsctl_port *port = node->data;
408         free(port);
409     }
410     shash_destroy(&info->ports);
411
412     SHASH_FOR_EACH (node, &info->ifaces) {
413         struct vsctl_iface *iface = node->data;
414         free(iface);
415     }
416     shash_destroy(&info->ifaces);
417 }
418
419 static void
420 get_info(const struct ovsrec_open_vswitch *ovs, struct vsctl_info *info)
421 {
422     struct shash bridges, ports;
423     size_t i;
424
425     shash_init(&info->bridges);
426     shash_init(&info->ports);
427     shash_init(&info->ifaces);
428
429     info->ctrl = ovs->controller;
430
431     shash_init(&bridges);
432     shash_init(&ports);
433     for (i = 0; i < ovs->n_bridges; i++) {
434         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
435         struct vsctl_bridge *br;
436         size_t j;
437
438         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
439             VLOG_WARN("%s: database contains duplicate bridge name",
440                       br_cfg->name);
441             continue;
442         }
443         br = add_bridge(info, br_cfg, br_cfg->name, NULL, 0);
444         if (!br) {
445             continue;
446         }
447
448         for (j = 0; j < br_cfg->n_ports; j++) {
449             struct ovsrec_port *port_cfg = br_cfg->ports[j];
450
451             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
452                 VLOG_WARN("%s: database contains duplicate port name",
453                           port_cfg->name);
454                 continue;
455             }
456
457             if (port_is_fake_bridge(port_cfg)
458                 && shash_add_once(&bridges, port_cfg->name, NULL)) {
459                 add_bridge(info, NULL, port_cfg->name, br, *port_cfg->tag);
460             }
461         }
462     }
463     shash_destroy(&bridges);
464     shash_destroy(&ports);
465
466     shash_init(&bridges);
467     shash_init(&ports);
468     for (i = 0; i < ovs->n_bridges; i++) {
469         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
470         struct vsctl_bridge *br;
471         size_t j;
472
473         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
474             continue;
475         }
476         br = shash_find_data(&info->bridges, br_cfg->name);
477         for (j = 0; j < br_cfg->n_ports; j++) {
478             struct ovsrec_port *port_cfg = br_cfg->ports[j];
479             struct vsctl_port *port;
480             size_t k;
481
482             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
483                 continue;
484             }
485
486             if (port_is_fake_bridge(port_cfg)
487                 && !shash_add_once(&bridges, port_cfg->name, NULL)) {
488                 continue;
489             }
490
491             port = xmalloc(sizeof *port);
492             port->port_cfg = port_cfg;
493             if (port_cfg->tag
494                 && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095) {
495                 port->bridge = find_vlan_bridge(info, br, *port_cfg->tag);
496                 if (!port->bridge) {
497                     port->bridge = br;
498                 }
499             } else {
500                 port->bridge = br;
501             }
502             shash_add(&info->ports, port_cfg->name, port);
503
504             for (k = 0; k < port_cfg->n_interfaces; k++) {
505                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
506                 struct vsctl_iface *iface;
507
508                 if (shash_find(&info->ifaces, iface_cfg->name)) {
509                     VLOG_WARN("%s: database contains duplicate interface name",
510                               iface_cfg->name);
511                     continue;
512                 }
513
514                 iface = xmalloc(sizeof *iface);
515                 iface->iface_cfg = iface_cfg;
516                 iface->port = port;
517                 shash_add(&info->ifaces, iface_cfg->name, iface);
518             }
519         }
520     }
521     shash_destroy(&bridges);
522     shash_destroy(&ports);
523 }
524
525 static void
526 check_conflicts(struct vsctl_info *info, const char *name,
527                 char *msg)
528 {
529     struct vsctl_iface *iface;
530     struct vsctl_port *port;
531
532     if (shash_find(&info->bridges, name)) {
533         vsctl_fatal("%s because a bridge named %s already exists",
534                     msg, name);
535     }
536
537     port = shash_find_data(&info->ports, name);
538     if (port) {
539         vsctl_fatal("%s because a port named %s already exists on "
540                     "bridge %s", msg, name, port->bridge->name);
541     }
542
543     iface = shash_find_data(&info->ifaces, name);
544     if (iface) {
545         vsctl_fatal("%s because an interface named %s already exists "
546                     "on bridge %s", msg, name, iface->port->bridge->name);
547     }
548
549     free(msg);
550 }
551
552 static struct vsctl_bridge *
553 find_bridge(struct vsctl_info *info, const char *name, bool must_exist)
554 {
555     struct vsctl_bridge *br = shash_find_data(&info->bridges, name);
556     if (must_exist && !br) {
557         vsctl_fatal("no bridge named %s", name);
558     }
559     return br;
560 }
561
562 static struct vsctl_bridge *
563 find_real_bridge(struct vsctl_info *info, const char *name, bool must_exist)
564 {
565     struct vsctl_bridge *br = find_bridge(info, name, must_exist);
566     if (br && br->parent) {
567         vsctl_fatal("%s is a fake bridge", name);
568     }
569     return br;
570 }
571
572 static struct vsctl_port *
573 find_port(struct vsctl_info *info, const char *name, bool must_exist)
574 {
575     struct vsctl_port *port = shash_find_data(&info->ports, name);
576     if (port && !strcmp(name, port->bridge->name)) {
577         port = NULL;
578     }
579     if (must_exist && !port) {
580         vsctl_fatal("no port named %s", name);
581     }
582     return port;
583 }
584
585 static struct vsctl_iface *
586 find_iface(struct vsctl_info *info, const char *name, bool must_exist)
587 {
588     struct vsctl_iface *iface = shash_find_data(&info->ifaces, name);
589     if (iface && !strcmp(name, iface->port->bridge->name)) {
590         iface = NULL;
591     }
592     if (must_exist && !iface) {
593         vsctl_fatal("no interface named %s", name);
594     }
595     return iface;
596 }
597
598 static void
599 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
600 {
601     struct ovsrec_port **ports;
602     size_t i;
603
604     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
605     for (i = 0; i < br->n_ports; i++) {
606         ports[i] = br->ports[i];
607     }
608     ports[br->n_ports] = port;
609     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
610     free(ports);
611 }
612
613 static void
614 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
615 {
616     struct ovsrec_port **ports;
617     size_t i, n;
618
619     ports = xmalloc(sizeof *br->ports * br->n_ports);
620     for (i = n = 0; i < br->n_ports; i++) {
621         if (br->ports[i] != port) {
622             ports[n++] = br->ports[i];
623         }
624     }
625     ovsrec_bridge_set_ports(br, ports, n);
626     free(ports);
627 }
628
629 static void
630 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
631                   struct ovsrec_bridge *bridge)
632 {
633     struct ovsrec_bridge **bridges;
634     size_t i;
635
636     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
637     for (i = 0; i < ovs->n_bridges; i++) {
638         bridges[i] = ovs->bridges[i];
639     }
640     bridges[ovs->n_bridges] = bridge;
641     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
642     free(bridges);
643 }
644
645 static void
646 ovs_delete_bridge(const struct ovsrec_open_vswitch *ovs,
647                   struct ovsrec_bridge *bridge)
648 {
649     struct ovsrec_bridge **bridges;
650     size_t i, n;
651
652     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
653     for (i = n = 0; i < ovs->n_bridges; i++) {
654         if (ovs->bridges[i] != bridge) {
655             bridges[n++] = ovs->bridges[i];
656         }
657     }
658     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
659     free(bridges);
660 }
661
662 static void
663 cmd_init(struct vsctl_context *ctx UNUSED)
664 {
665 }
666
667 static void
668 cmd_add_br(struct vsctl_context *ctx)
669 {
670     const char *br_name = ctx->argv[1];
671     struct vsctl_info info;
672
673     get_info(ctx->ovs, &info);
674     check_conflicts(&info, br_name,
675                     xasprintf("cannot create a bridge named %s", br_name));
676
677     if (ctx->argc == 2) {
678         struct ovsrec_bridge *br;
679         struct ovsrec_port *port;
680         struct ovsrec_interface *iface;
681
682         iface = ovsrec_interface_insert(txn_from_openvswitch(ctx->ovs));
683         ovsrec_interface_set_name(iface, br_name);
684
685         port = ovsrec_port_insert(txn_from_openvswitch(ctx->ovs));
686         ovsrec_port_set_name(port, br_name);
687         ovsrec_port_set_interfaces(port, &iface, 1);
688
689         br = ovsrec_bridge_insert(txn_from_openvswitch(ctx->ovs));
690         ovsrec_bridge_set_name(br, br_name);
691         ovsrec_bridge_set_ports(br, &port, 1);
692
693         ovs_insert_bridge(ctx->ovs, br);
694     } else if (ctx->argc == 3) {
695         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
696                     ctx->argv[0]);
697     } else if (ctx->argc == 4) {
698         const char *parent_name = ctx->argv[2];
699         int vlan = atoi(ctx->argv[3]);
700         struct ovsrec_bridge *br;
701         struct vsctl_bridge *parent;
702         struct ovsrec_port *port;
703         struct ovsrec_interface *iface;
704         int64_t tag = vlan;
705
706         if (vlan < 1 || vlan > 4095) {
707             vsctl_fatal("%s: vlan must be between 1 and 4095", ctx->argv[0]);
708         }
709
710         parent = find_bridge(&info, parent_name, false);
711         if (parent && parent->vlan) {
712             vsctl_fatal("cannot create bridge with fake bridge as parent");
713         }
714         if (!parent) {
715             vsctl_fatal("parent bridge %s does not exist", parent_name);
716         }
717         br = parent->br_cfg;
718
719         iface = ovsrec_interface_insert(txn_from_openvswitch(ctx->ovs));
720         ovsrec_interface_set_name(iface, br_name);
721         ovsrec_interface_set_type(iface, "internal");
722
723         port = ovsrec_port_insert(txn_from_openvswitch(ctx->ovs));
724         ovsrec_port_set_name(port, br_name);
725         ovsrec_port_set_interfaces(port, &iface, 1);
726         ovsrec_port_set_fake_bridge(port, true);
727         ovsrec_port_set_tag(port, &tag, 1);
728
729         bridge_insert_port(br, port);
730     } else {
731         NOT_REACHED();
732     }
733
734     free_info(&info);
735 }
736
737 static void
738 del_port(struct vsctl_info *info, struct vsctl_port *port)
739 {
740     struct shash_node *node;
741
742     SHASH_FOR_EACH (node, &info->ifaces) {
743         struct vsctl_iface *iface = node->data;
744         if (iface->port == port) {
745             ovsrec_interface_delete(iface->iface_cfg);
746         }
747     }
748     ovsrec_port_delete(port->port_cfg);
749
750     bridge_delete_port((port->bridge->parent
751                         ? port->bridge->parent->br_cfg
752                         : port->bridge->br_cfg), port->port_cfg);
753 }
754
755 static void
756 cmd_del_br(struct vsctl_context *ctx)
757 {
758     bool must_exist = !shash_find(&ctx->options, "--if-exists");
759     struct vsctl_bridge *bridge;
760     struct vsctl_info info;
761
762     get_info(ctx->ovs, &info);
763     bridge = find_bridge(&info, ctx->argv[1], must_exist);
764     if (bridge) {
765         struct shash_node *node;
766
767         SHASH_FOR_EACH (node, &info.ports) {
768             struct vsctl_port *port = node->data;
769             if (port->bridge == bridge
770                 || !strcmp(port->port_cfg->name, bridge->name)) {
771                 del_port(&info, port);
772             }
773         }
774         if (bridge->br_cfg) {
775             ovsrec_bridge_delete(bridge->br_cfg);
776             ovs_delete_bridge(ctx->ovs, bridge->br_cfg);
777         }
778     }
779     free_info(&info);
780 }
781
782 static void
783 output_sorted(struct svec *svec, struct ds *output)
784 {
785     const char *name;
786     size_t i;
787
788     svec_sort(svec);
789     SVEC_FOR_EACH (i, name, svec) {
790         ds_put_format(output, "%s\n", name);
791     }
792 }
793
794 static void
795 cmd_list_br(struct vsctl_context *ctx)
796 {
797     struct shash_node *node;
798     struct vsctl_info info;
799     struct svec bridges;
800
801     get_info(ctx->ovs, &info);
802
803     svec_init(&bridges);
804     SHASH_FOR_EACH (node, &info.bridges) {
805         struct vsctl_bridge *br = node->data;
806         svec_add(&bridges, br->name);
807     }
808     output_sorted(&bridges, &ctx->output);
809     svec_destroy(&bridges);
810
811     free_info(&info);
812 }
813
814 static void
815 cmd_br_exists(struct vsctl_context *ctx)
816 {
817     struct vsctl_info info;
818
819     get_info(ctx->ovs, &info);
820     if (!find_bridge(&info, ctx->argv[1], false)) {
821         exit(2);
822     }
823     free_info(&info);
824 }
825
826 /* Returns true if 'b_prefix' (of length 'b_prefix_len') concatenated with 'b'
827  * equals 'a', false otherwise. */
828 static bool
829 key_matches(const char *a,
830             const char *b_prefix, size_t b_prefix_len, const char *b)
831 {
832     return !strncmp(a, b_prefix, b_prefix_len) && !strcmp(a + b_prefix_len, b);
833 }
834
835 static void
836 set_external_id(char **old_keys, char **old_values, size_t old_n,
837                 char *key, char *value,
838                 char ***new_keysp, char ***new_valuesp, size_t *new_np)
839 {
840     char **new_keys;
841     char **new_values;
842     size_t new_n;
843     size_t i;
844
845     new_keys = xmalloc(sizeof *new_keys * (old_n + 1));
846     new_values = xmalloc(sizeof *new_values * (old_n + 1));
847     new_n = 0;
848     for (i = 0; i < old_n; i++) {
849         if (strcmp(key, old_keys[i])) {
850             new_keys[new_n] = old_keys[i];
851             new_values[new_n] = old_values[i];
852             new_n++;
853         }
854     }
855     if (value) {
856         new_keys[new_n] = key;
857         new_values[new_n] = value;
858         new_n++;
859     }
860     *new_keysp = new_keys;
861     *new_valuesp = new_values;
862     *new_np = new_n;
863 }
864
865 static void
866 cmd_br_set_external_id(struct vsctl_context *ctx)
867 {
868     struct vsctl_info info;
869     struct vsctl_bridge *bridge;
870     char **keys, **values;
871     size_t n;
872
873     get_info(ctx->ovs, &info);
874     bridge = find_bridge(&info, ctx->argv[1], true);
875     if (bridge->br_cfg) {
876         set_external_id(bridge->br_cfg->key_external_ids,
877                         bridge->br_cfg->value_external_ids,
878                         bridge->br_cfg->n_external_ids,
879                         ctx->argv[2], ctx->argc >= 4 ? ctx->argv[3] : NULL,
880                         &keys, &values, &n);
881         ovsrec_bridge_set_external_ids(bridge->br_cfg, keys, values, n);
882     } else {
883         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
884         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
885         set_external_id(port->port_cfg->key_external_ids,
886                         port->port_cfg->value_external_ids,
887                         port->port_cfg->n_external_ids,
888                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL,
889                         &keys, &values, &n);
890         ovsrec_port_set_external_ids(port->port_cfg, keys, values, n);
891         free(key);
892     }
893     free(keys);
894     free(values);
895
896     free_info(&info);
897 }
898
899 static void
900 get_external_id(char **keys, char **values, size_t n,
901                 const char *prefix, const char *key,
902                 struct ds *output)
903 {
904     size_t prefix_len = strlen(prefix);
905     struct svec svec;
906     size_t i;
907
908     svec_init(&svec);
909     for (i = 0; i < n; i++) {
910         if (!key && !strncmp(keys[i], prefix, prefix_len)) {
911             svec_add_nocopy(&svec, xasprintf("%s=%s",
912                                              keys[i] + prefix_len, values[i]));
913         } else if (key_matches(keys[i], prefix, prefix_len, key)) {
914             svec_add(&svec, values[i]);
915             break;
916         }
917     }
918     output_sorted(&svec, output);
919     svec_destroy(&svec);
920 }
921
922 static void
923 cmd_br_get_external_id(struct vsctl_context *ctx)
924 {
925     struct vsctl_info info;
926     struct vsctl_bridge *bridge;
927
928     get_info(ctx->ovs, &info);
929     bridge = find_bridge(&info, ctx->argv[1], true);
930     if (bridge->br_cfg) {
931         get_external_id(bridge->br_cfg->key_external_ids,
932                         bridge->br_cfg->value_external_ids,
933                         bridge->br_cfg->n_external_ids,
934                         "", ctx->argc >= 3 ? ctx->argv[2] : NULL,
935                         &ctx->output);
936     } else {
937         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
938         get_external_id(port->port_cfg->key_external_ids,
939                         port->port_cfg->value_external_ids,
940                         port->port_cfg->n_external_ids,
941                         "fake-bridge-", ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
942     }
943     free_info(&info);
944 }
945
946
947 static void
948 cmd_list_ports(struct vsctl_context *ctx)
949 {
950     struct vsctl_bridge *br;
951     struct shash_node *node;
952     struct vsctl_info info;
953     struct svec ports;
954
955     get_info(ctx->ovs, &info);
956     br = find_bridge(&info, ctx->argv[1], true);
957
958     svec_init(&ports);
959     SHASH_FOR_EACH (node, &info.ports) {
960         struct vsctl_port *port = node->data;
961
962         if (strcmp(port->port_cfg->name, br->name) && br == port->bridge) {
963             svec_add(&ports, port->port_cfg->name);
964         }
965     }
966     output_sorted(&ports, &ctx->output);
967     svec_destroy(&ports);
968
969     free_info(&info);
970 }
971
972 static void
973 add_port(const struct ovsrec_open_vswitch *ovs,
974          const char *br_name, const char *port_name, bool fake_iface,
975          char *iface_names[], int n_ifaces)
976 {
977     struct vsctl_info info;
978     struct vsctl_bridge *bridge;
979     struct ovsrec_interface **ifaces;
980     struct ovsrec_port *port;
981     size_t i;
982
983     get_info(ovs, &info);
984     check_conflicts(&info, port_name,
985                     xasprintf("cannot create a port named %s", port_name));
986     /* XXX need to check for conflicts on interfaces too */
987     bridge = find_bridge(&info, br_name, true);
988
989     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
990     for (i = 0; i < n_ifaces; i++) {
991         ifaces[i] = ovsrec_interface_insert(txn_from_openvswitch(ovs));
992         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
993     }
994
995     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
996     ovsrec_port_set_name(port, port_name);
997     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
998     ovsrec_port_set_bond_fake_iface(port, fake_iface);
999     free(ifaces);
1000
1001     if (bridge->vlan) {
1002         int64_t tag = bridge->vlan;
1003         ovsrec_port_set_tag(port, &tag, 1);
1004     }
1005
1006     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1007                         : bridge->br_cfg), port);
1008
1009     free_info(&info);
1010 }
1011
1012 static void
1013 cmd_add_port(struct vsctl_context *ctx)
1014 {
1015     add_port(ctx->ovs, ctx->argv[1], ctx->argv[2], false, &ctx->argv[2], 1);
1016 }
1017
1018 static void
1019 cmd_add_bond(struct vsctl_context *ctx)
1020 {
1021     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1022
1023     add_port(ctx->ovs, ctx->argv[1], ctx->argv[2], fake_iface,
1024              &ctx->argv[3], ctx->argc - 3);
1025 }
1026
1027 static void
1028 cmd_del_port(struct vsctl_context *ctx)
1029 {
1030     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1031     struct vsctl_info info;
1032
1033     get_info(ctx->ovs, &info);
1034     if (ctx->argc == 2) {
1035         struct vsctl_port *port = find_port(&info, ctx->argv[1], must_exist);
1036         if (port) {
1037             del_port(&info, port);
1038         }
1039     } else if (ctx->argc == 3) {
1040         struct vsctl_bridge *bridge = find_bridge(&info, ctx->argv[1], true);
1041         struct vsctl_port *port = find_port(&info, ctx->argv[2], must_exist);
1042
1043         if (port) {
1044             if (port->bridge == bridge) {
1045                 del_port(&info, port);
1046             } else if (port->bridge->parent == bridge) {
1047                 vsctl_fatal("bridge %s does not have a port %s (although its "
1048                             "parent bridge %s does)",
1049                             ctx->argv[1], ctx->argv[2], bridge->parent->name);
1050             } else {
1051                 vsctl_fatal("bridge %s does not have a port %s",
1052                             ctx->argv[1], ctx->argv[2]);
1053             }
1054         }
1055     }
1056     free_info(&info);
1057 }
1058
1059 static void
1060 cmd_port_to_br(struct vsctl_context *ctx)
1061 {
1062     struct vsctl_port *port;
1063     struct vsctl_info info;
1064
1065     get_info(ctx->ovs, &info);
1066     port = find_port(&info, ctx->argv[1], true);
1067     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
1068     free_info(&info);
1069 }
1070
1071 static void
1072 cmd_br_to_vlan(struct vsctl_context *ctx)
1073 {
1074     struct vsctl_bridge *bridge;
1075     struct vsctl_info info;
1076
1077     get_info(ctx->ovs, &info);
1078     bridge = find_bridge(&info, ctx->argv[1], true);
1079     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
1080     free_info(&info);
1081 }
1082
1083 static void
1084 cmd_br_to_parent(struct vsctl_context *ctx)
1085 {
1086     struct vsctl_bridge *bridge;
1087     struct vsctl_info info;
1088
1089     get_info(ctx->ovs, &info);
1090     bridge = find_bridge(&info, ctx->argv[1], true);
1091     if (bridge->parent) {
1092         bridge = bridge->parent;
1093     }
1094     ds_put_format(&ctx->output, "%s\n", bridge->name);
1095     free_info(&info);
1096 }
1097
1098 static void
1099 cmd_list_ifaces(struct vsctl_context *ctx)
1100 {
1101     struct vsctl_bridge *br;
1102     struct shash_node *node;
1103     struct vsctl_info info;
1104     struct svec ifaces;
1105
1106     get_info(ctx->ovs, &info);
1107     br = find_bridge(&info, ctx->argv[1], true);
1108
1109     svec_init(&ifaces);
1110     SHASH_FOR_EACH (node, &info.ifaces) {
1111         struct vsctl_iface *iface = node->data;
1112
1113         if (strcmp(iface->iface_cfg->name, br->name)
1114             && br == iface->port->bridge) {
1115             svec_add(&ifaces, iface->iface_cfg->name);
1116         }
1117     }
1118     output_sorted(&ifaces, &ctx->output);
1119     svec_destroy(&ifaces);
1120
1121     free_info(&info);
1122 }
1123
1124 static void
1125 cmd_iface_to_br(struct vsctl_context *ctx)
1126 {
1127     struct vsctl_iface *iface;
1128     struct vsctl_info info;
1129
1130     get_info(ctx->ovs, &info);
1131     iface = find_iface(&info, ctx->argv[1], true);
1132     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
1133     free_info(&info);
1134 }
1135
1136 static void
1137 cmd_get_controller(struct vsctl_context *ctx)
1138 {
1139     struct vsctl_info info;
1140
1141     get_info(ctx->ovs, &info);
1142
1143     if (ctx->argc == 1) {
1144         /* Return the controller from the "Open_vSwitch" table */
1145         if (info.ctrl) {
1146             ds_put_format(&ctx->output, "%s\n", info.ctrl->target);
1147         }
1148     } else {
1149         /* Return the controller for a particular bridge. */
1150         struct vsctl_bridge *br = find_bridge(&info, ctx->argv[1], true);
1151
1152         /* If no controller is explicitly defined for the requested
1153          * bridge, fallback to the "Open_vSwitch" table's controller. */
1154         if (br->ctrl) {
1155             ds_put_format(&ctx->output, "%s\n", br->ctrl->target);
1156         } else if (info.ctrl) {
1157             ds_put_format(&ctx->output, "%s\n", info.ctrl->target);
1158         }
1159     }
1160
1161     free_info(&info);
1162 }
1163
1164 static void
1165 cmd_del_controller(struct vsctl_context *ctx)
1166 {
1167     struct vsctl_info info;
1168
1169     get_info(ctx->ovs, &info);
1170
1171     if (ctx->argc == 1) {
1172         if (info.ctrl) {
1173             ovsrec_controller_delete(info.ctrl);
1174             ovsrec_open_vswitch_set_controller(ctx->ovs, NULL);
1175         }
1176     } else {
1177         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1178
1179         if (br->ctrl) {
1180             ovsrec_controller_delete(br->ctrl);
1181             ovsrec_bridge_set_controller(br->br_cfg, NULL);
1182         }
1183     }
1184
1185     free_info(&info);
1186 }
1187
1188 static void
1189 cmd_set_controller(struct vsctl_context *ctx)
1190 {
1191     struct vsctl_info info;
1192     struct ovsrec_controller *ctrl;
1193
1194     get_info(ctx->ovs, &info);
1195
1196     if (ctx->argc == 2) {
1197         /* Set the controller in the "Open_vSwitch" table. */
1198         if (info.ctrl) {
1199             ovsrec_controller_delete(info.ctrl);
1200         }
1201         ctrl = ovsrec_controller_insert(txn_from_openvswitch(ctx->ovs));
1202         ovsrec_controller_set_target(ctrl, ctx->argv[1]);
1203         ovsrec_open_vswitch_set_controller(ctx->ovs, ctrl);
1204     } else {
1205         /* Set the controller for a particular bridge. */
1206         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1207
1208         if (br->ctrl) {
1209             ovsrec_controller_delete(br->ctrl);
1210         }
1211         ctrl = ovsrec_controller_insert(txn_from_openvswitch(ctx->ovs));
1212         ovsrec_controller_set_target(ctrl, ctx->argv[2]);
1213         ovsrec_bridge_set_controller(br->br_cfg, ctrl);
1214     }
1215
1216     free_info(&info);
1217 }
1218
1219 static void
1220 cmd_get_fail_mode(struct vsctl_context *ctx)
1221 {
1222     struct vsctl_info info;
1223     const char *fail_mode = NULL;
1224
1225     get_info(ctx->ovs, &info);
1226
1227     if (ctx->argc == 1) {
1228         /* Return the fail-mode from the "Open_vSwitch" table */
1229         if (info.ctrl && info.ctrl->fail_mode) {
1230             fail_mode = info.ctrl->fail_mode;
1231         }
1232     } else {
1233         /* Return the fail-mode for a particular bridge. */
1234         struct vsctl_bridge *br = find_bridge(&info, ctx->argv[1], true);
1235
1236         /* If no controller or fail-mode is explicitly defined for the 
1237          * requested bridge, fallback to the "Open_vSwitch" table's 
1238          * setting. */
1239         if (br->ctrl && br->ctrl->fail_mode) {
1240             fail_mode = br->ctrl->fail_mode;
1241         } else if (info.ctrl && info.ctrl->fail_mode) {
1242             fail_mode = info.ctrl->fail_mode;
1243         }
1244     }
1245
1246     if (fail_mode && strlen(fail_mode)) {
1247         ds_put_format(&ctx->output, "%s\n", fail_mode);
1248     }
1249
1250     free_info(&info);
1251 }
1252
1253 static void
1254 cmd_del_fail_mode(struct vsctl_context *ctx)
1255 {
1256     struct vsctl_info info;
1257
1258     get_info(ctx->ovs, &info);
1259
1260     if (ctx->argc == 1) {
1261         if (info.ctrl && info.ctrl->fail_mode) {
1262             ovsrec_controller_set_fail_mode(info.ctrl, NULL);
1263         }
1264     } else {
1265         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1266
1267         if (br->ctrl && br->ctrl->fail_mode) {
1268             ovsrec_controller_set_fail_mode(br->ctrl, NULL);
1269         }
1270     }
1271
1272     free_info(&info);
1273 }
1274
1275 static void
1276 cmd_set_fail_mode(struct vsctl_context *ctx)
1277 {
1278     struct vsctl_info info;
1279     const char *fail_mode;
1280
1281     get_info(ctx->ovs, &info);
1282
1283     fail_mode = (ctx->argc == 2) ? ctx->argv[1] : ctx->argv[2];
1284
1285     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
1286         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
1287     }
1288
1289     if (ctx->argc == 2) {
1290         /* Set the fail-mode in the "Open_vSwitch" table. */
1291         if (!info.ctrl) {
1292             vsctl_fatal("no controller declared");
1293         }
1294         ovsrec_controller_set_fail_mode(info.ctrl, fail_mode);
1295     } else {
1296         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1297
1298         if (!br->ctrl) {
1299             vsctl_fatal("no controller declared for %s", br->name);
1300         }
1301         ovsrec_controller_set_fail_mode(br->ctrl, fail_mode);
1302     }
1303
1304     free_info(&info);
1305 }
1306
1307 static void
1308 cmd_get_ssl(struct vsctl_context *ctx)
1309 {
1310     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1311
1312     if (ssl) {
1313         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
1314         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
1315         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
1316         ds_put_format(&ctx->output, "Bootstrap: %s\n",
1317                 ssl->bootstrap_ca_cert ? "true" : "false");
1318     }
1319 }
1320
1321 static void
1322 cmd_del_ssl(struct vsctl_context *ctx)
1323 {
1324     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1325
1326     if (ssl) {
1327         ovsrec_ssl_delete(ssl);
1328         ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1329     }
1330 }
1331
1332 static void
1333 cmd_set_ssl(struct vsctl_context *ctx)
1334 {
1335     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
1336     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1337
1338     if (ssl) {
1339         ovsrec_ssl_delete(ssl);
1340     }
1341     ssl = ovsrec_ssl_insert(txn_from_openvswitch(ctx->ovs));
1342
1343     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
1344     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
1345     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
1346
1347     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
1348
1349     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
1350 }
1351 \f
1352 /* Parameter commands. */
1353
1354 /* POSIX extended regular expression for an 8-bit unsigned decimal integer. */
1355 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
1356
1357 /* POSIX extended regular expression for an IP address. */
1358 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
1359
1360 /* POSIX extended regular expression for a netmask. */
1361 #define NETMASK_RE                              \
1362         "255.255.255."NETMASK_END_RE"|"         \
1363         "255.255."NETMASK_END_RE".0|"           \
1364         "255."NETMASK_END_RE".0.0|"             \
1365         NETMASK_END_RE".0.0.0"
1366 #define NETMASK_END_RE "(255|254|252|248|240|224|192|128|0)"
1367
1368 /* POSIX extended regular expression for an Ethernet address. */
1369 #define XX_RE "[0-9a-fA-F][0-9a-fA-F]"
1370 #define MAC_RE XX_RE":"XX_RE":"XX_RE":"XX_RE":"XX_RE":"XX_RE
1371
1372 /* POSIX extended regular expression for a TCP or UDP port number. */
1373 #define PORT_RE                                 \
1374     "([0-9]|"                                   \
1375     "[1-9][0-9]|"                               \
1376     "[1-9][0-9][0-9]|"                          \
1377     "[1-9][0-9][0-9][0-9]|"                     \
1378     "[1-5][0-9][0-9][0-9][0-9]|"                \
1379     "6[1-4][0-9][0-9][0-9]|"                    \
1380     "65[1-4][0-9][0-9]|"                        \
1381     "655[1-2][0-9]|"                            \
1382     "6553[1-5])"
1383
1384 enum {
1385     VSCF_READONLY = 1 << 0,
1386     VSCF_HIDDEN = 1 << 1
1387 };
1388
1389 struct vsctl_column {
1390     struct ovsdb_idl_column *idl;
1391     int flags;
1392     const char *constraint;
1393 };
1394
1395 static const struct vsctl_column bridge_columns[] = {
1396     {&ovsrec_bridge_col_datapath_id, VSCF_READONLY, NULL},
1397     {&ovsrec_bridge_col_name, VSCF_READONLY, NULL},
1398     {&ovsrec_bridge_col_mirrors, VSCF_READONLY, NULL},
1399     {&ovsrec_bridge_col_other_config, 0, NULL},
1400     {&ovsrec_bridge_col_flood_vlans, 0, "[1,4095]"},
1401     {&ovsrec_bridge_col_controller, VSCF_READONLY, NULL},
1402     {&ovsrec_bridge_col_netflow, VSCF_READONLY, NULL},
1403     {&ovsrec_bridge_col_external_ids, 0, NULL},
1404     {&ovsrec_bridge_col_ports, VSCF_READONLY, NULL},
1405     {NULL, 0, NULL},
1406 };
1407
1408 static const struct vsctl_column controller_columns[] = {
1409     {&ovsrec_controller_col_connection_mode, 0, "in-band|out-of-band"},
1410     {&ovsrec_controller_col_controller_burst_limit, 0, "[25,]"},
1411     {&ovsrec_controller_col_controller_rate_limit, 0, "[100,]"},
1412     {&ovsrec_controller_col_discover_accept_regex, 0, NULL},
1413     {&ovsrec_controller_col_discover_update_resolv_conf, 0, NULL},
1414     {&ovsrec_controller_col_fail_mode, 0, "standalone|secure"},
1415     {&ovsrec_controller_col_inactivity_probe, 0, "[5000,]"},
1416     {&ovsrec_controller_col_local_gateway, 0, IP_RE},
1417     {&ovsrec_controller_col_local_ip, 0, IP_RE},
1418     {&ovsrec_controller_col_local_netmask, 0, NETMASK_RE},
1419     {&ovsrec_controller_col_max_backoff, 0, "[1000,]"},
1420     {&ovsrec_controller_col_target, 0, NULL},
1421     {NULL, 0, NULL},
1422 };
1423
1424 static const struct vsctl_column interface_columns[] = {
1425     {&ovsrec_interface_col_external_ids, 0, NULL},
1426     {&ovsrec_interface_col_ingress_policing_burst, 0, "[10,]"},
1427     {&ovsrec_interface_col_ingress_policing_rate, 0, "[100,]"},
1428     {&ovsrec_interface_col_mac, 0, MAC_RE},
1429     {&ovsrec_interface_col_name, VSCF_READONLY, NULL},
1430     {&ovsrec_interface_col_ofport, VSCF_READONLY, NULL},
1431     {&ovsrec_interface_col_options, 0, NULL},
1432     {&ovsrec_interface_col_type, VSCF_READONLY, NULL},
1433     {NULL, 0, NULL},
1434 };
1435
1436 static const struct vsctl_column mirror_columns[] = {
1437     {&ovsrec_mirror_col_name, VSCF_READONLY, NULL},
1438     {&ovsrec_mirror_col_output_port, 0, "Port"},
1439     {&ovsrec_mirror_col_output_vlan, 0, "[1,4095]"},
1440     {&ovsrec_mirror_col_select_dst_port, 0, "Port"},
1441     {&ovsrec_mirror_col_select_src_port, 0, "Port"},
1442     {&ovsrec_mirror_col_select_vlan, 0, "[1,4095]"},
1443     {NULL, 0, NULL},
1444 };
1445
1446 static const struct vsctl_column netflow_columns[] = {
1447     {&ovsrec_netflow_col_active_timeout, 0, "[-1,]"},
1448     {&ovsrec_netflow_col_add_id_to_interface, 0, NULL},
1449     {&ovsrec_netflow_col_targets, 0, IP_RE":"PORT_RE},
1450     {&ovsrec_netflow_col_engine_type, 0, "[0,255]"},
1451     {&ovsrec_netflow_col_engine_id, 0, "[0,255]"},
1452     {NULL, 0, NULL},
1453 };
1454
1455 static const struct vsctl_column open_vswitch_columns[] = {
1456     {&ovsrec_open_vswitch_col_bridges, VSCF_READONLY, NULL},
1457     {&ovsrec_open_vswitch_col_controller, VSCF_READONLY, NULL},
1458     {&ovsrec_open_vswitch_col_cur_cfg, VSCF_HIDDEN, NULL},
1459     {&ovsrec_open_vswitch_col_management_id, 0, "[0-9a-fA-F]{12}"},
1460     {&ovsrec_open_vswitch_col_managers, 0, "p?(ssl|tcp|unix):.*"},
1461     {&ovsrec_open_vswitch_col_next_cfg, VSCF_HIDDEN, NULL},
1462     {&ovsrec_open_vswitch_col_ssl, VSCF_READONLY, NULL},
1463     {NULL, 0, NULL},
1464 };
1465
1466 static const struct vsctl_column port_columns[] = {
1467     {&ovsrec_port_col_bond_updelay, 0, "[0,]"},
1468     {&ovsrec_port_col_bond_downdelay, 0, "[0,]"},
1469     {&ovsrec_port_col_bond_fake_iface, VSCF_READONLY, NULL},
1470     {&ovsrec_port_col_external_ids, 0, NULL},
1471     {&ovsrec_port_col_fake_bridge, VSCF_READONLY, NULL},
1472     {&ovsrec_port_col_interfaces, VSCF_READONLY, NULL},
1473     {&ovsrec_port_col_mac, 0, MAC_RE},
1474     {&ovsrec_port_col_name, VSCF_READONLY, NULL},
1475     {&ovsrec_port_col_other_config, 0, NULL},
1476     {&ovsrec_port_col_tag, 0, "[0,4095]"},
1477     {&ovsrec_port_col_trunks, 0, "[0,4095]"},
1478     {NULL, 0, NULL},
1479 };
1480
1481 static const struct vsctl_column ssl_columns[] = {
1482     {&ovsrec_ssl_col_bootstrap_ca_cert, 0, NULL},
1483     {&ovsrec_ssl_col_ca_cert, 0, NULL},
1484     {&ovsrec_ssl_col_certificate, 0, NULL},
1485     {&ovsrec_ssl_col_private_key, 0, NULL},
1486     {NULL, 0, NULL},
1487 };
1488
1489 struct vsctl_row_id {
1490     const struct ovsdb_idl_table_class *table;
1491     const struct ovsdb_idl_column *name_column;
1492     const struct ovsdb_idl_column *uuid_column;
1493 };
1494
1495 struct vsctl_table_class {
1496     struct ovsdb_idl_table_class *class;
1497     const struct vsctl_column *columns;
1498     struct vsctl_row_id row_ids[2];
1499 };
1500
1501 static const struct vsctl_table_class tables[] = {
1502     {&ovsrec_table_bridge, bridge_columns,
1503      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
1504       {NULL, NULL, NULL}}},
1505
1506     {&ovsrec_table_controller, controller_columns,
1507      {{&ovsrec_table_bridge,
1508        &ovsrec_bridge_col_name,
1509        &ovsrec_bridge_col_controller},
1510       {&ovsrec_table_open_vswitch,
1511        NULL,
1512        &ovsrec_open_vswitch_col_controller}}},
1513
1514     {&ovsrec_table_interface, interface_columns,
1515      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
1516       {NULL, NULL, NULL}}},
1517
1518     {&ovsrec_table_mirror, mirror_columns,
1519      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
1520       {NULL, NULL, NULL}}},
1521
1522     {&ovsrec_table_netflow, netflow_columns,
1523      {{&ovsrec_table_bridge,
1524        &ovsrec_bridge_col_name,
1525        &ovsrec_bridge_col_netflow},
1526       {NULL, NULL, NULL}}},
1527
1528     {&ovsrec_table_open_vswitch, open_vswitch_columns,
1529      {{&ovsrec_table_open_vswitch, NULL, NULL},
1530       {NULL, NULL, NULL}}},
1531
1532     {&ovsrec_table_port, port_columns,
1533      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
1534       {NULL, NULL, NULL}}},
1535
1536     {&ovsrec_table_ssl, ssl_columns,
1537      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
1538
1539     {NULL, NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1540 };
1541
1542 static void
1543 die_if_error(char *error)
1544 {
1545     if (error) {
1546         ovs_fatal(0, "%s", error);
1547     }
1548 }
1549
1550 static int
1551 to_lower_and_underscores(unsigned c)
1552 {
1553     return c == '-' ? '_' : tolower(c);
1554 }
1555
1556 static unsigned int
1557 score_partial_match(const char *name, const char *s)
1558 {
1559     int score;
1560
1561     if (!strcmp(name, s)) {
1562         return UINT_MAX;
1563     }
1564     for (score = 0; ; score++, name++, s++) {
1565         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
1566             break;
1567         } else if (*name == '\0') {
1568             return UINT_MAX - 1;
1569         }
1570     }
1571     return *s == '\0' ? score : 0;
1572 }
1573
1574 static const struct vsctl_table_class *
1575 get_table(const char *table_name)
1576 {
1577     const struct vsctl_table_class *table;
1578     const struct vsctl_table_class *best_match = NULL;
1579     unsigned int best_score = 0;
1580
1581     for (table = tables; table->class; table++) {
1582         unsigned int score = score_partial_match(table->class->name,
1583                                                  table_name);
1584         if (score > best_score) {
1585             best_match = table;
1586             best_score = score;
1587         } else if (score == best_score) {
1588             best_match = NULL;
1589         }
1590     }
1591     if (best_match) {
1592         return best_match;
1593     } else if (best_score) {
1594         ovs_fatal(0, "multiple table names match \"%s\"", table_name);
1595     } else {
1596         ovs_fatal(0, "unknown table \"%s\"", table_name);
1597     }
1598 }
1599
1600 static const struct ovsdb_idl_row *
1601 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
1602               const struct vsctl_row_id *id, const char *record_id)
1603 {
1604     const struct ovsdb_idl_row *referrer, *final;
1605
1606     if (!id->table) {
1607         return NULL;
1608     }
1609
1610     if (!id->name_column) {
1611         if (strcmp(record_id, ".")) {
1612             return NULL;
1613         }
1614         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
1615         if (!referrer || ovsdb_idl_next_row(referrer)) {
1616             return NULL;
1617         }
1618     } else {
1619         const struct ovsdb_idl_row *row;
1620         unsigned int best_score = 0;
1621
1622         /* It might make sense to relax this assertion. */
1623         assert(id->name_column->type.key_type == OVSDB_TYPE_STRING);
1624
1625         referrer = NULL;
1626         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
1627              row != NULL && best_score != UINT_MAX;
1628              row = ovsdb_idl_next_row(row))
1629         {
1630             struct ovsdb_datum name;
1631
1632             ovsdb_idl_txn_read(row, id->name_column, &name);
1633             if (name.n == 1) {
1634                 unsigned int score = score_partial_match(name.keys[0].string,
1635                                                          record_id);
1636                 if (score > best_score) {
1637                     referrer = row;
1638                     best_score = score;
1639                 } else if (score == best_score) {
1640                     referrer = NULL;
1641                 }
1642             }
1643             ovsdb_datum_destroy(&name, &id->name_column->type);
1644         }
1645     }
1646     if (!referrer) {
1647         return NULL;
1648     }
1649
1650     final = NULL;
1651     if (id->uuid_column) {
1652         struct ovsdb_datum uuid;
1653
1654         assert(id->uuid_column->type.key_type == OVSDB_TYPE_UUID);
1655         assert(id->uuid_column->type.value_type == OVSDB_TYPE_VOID);
1656
1657         ovsdb_idl_txn_read(referrer, id->uuid_column, &uuid);
1658         if (uuid.n == 1) {
1659             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
1660                                                &uuid.keys[0].uuid);
1661         }
1662         ovsdb_datum_destroy(&uuid, &id->uuid_column->type);
1663     } else {
1664         final = referrer;
1665     }
1666
1667     return final;
1668 }
1669
1670 static const struct ovsdb_idl_row *
1671 get_row(struct vsctl_context *ctx,
1672         const struct vsctl_table_class *table, const char *record_id)
1673 {
1674     const struct ovsdb_idl_row *row;
1675     struct uuid uuid;
1676
1677     if (uuid_from_string(&uuid, record_id)) {
1678         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
1679     } else {
1680         int i;
1681
1682         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
1683             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
1684             if (row) {
1685                 break;
1686             }
1687         }
1688     }
1689     return row;
1690 }
1691
1692 static const struct ovsdb_idl_row *
1693 must_get_row(struct vsctl_context *ctx,
1694              const struct vsctl_table_class *table, const char *record_id)
1695 {
1696     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
1697     if (!row) {
1698         ovs_fatal(0, "no row \"%s\" in table %s",
1699                   record_id, table->class->name);
1700     }
1701     return row;
1702 }
1703
1704 static char *
1705 get_column(const struct vsctl_table_class *table, const char *column_name,
1706            const struct vsctl_column **columnp)
1707 {
1708     const struct vsctl_column *column;
1709     const struct vsctl_column *best_match = NULL;
1710     unsigned int best_score = 0;
1711
1712     for (column = table->columns; column->idl; column++) {
1713         if (!(column->flags & VSCF_HIDDEN)) {
1714             unsigned int score = score_partial_match(column->idl->name,
1715                                                      column_name);
1716             if (score > best_score) {
1717                 best_match = column;
1718                 best_score = score;
1719             } else if (score == best_score) {
1720                 best_match = NULL;
1721             }
1722         }
1723     }
1724
1725     *columnp = best_match;
1726     if (best_match) {
1727         return NULL;
1728     } else if (best_score) {
1729         return xasprintf("%s contains more than one column whose name "
1730                          "matches \"%s\"", table->class->name, column_name);
1731     } else {
1732         return xasprintf("%s does not contain a column whose name matches "
1733                          "\"%s\"", table->class->name, column_name);
1734     }
1735 }
1736
1737 static char * WARN_UNUSED_RESULT
1738 parse_column_key_value(const char *arg, const struct vsctl_table_class *table,
1739                        const struct vsctl_column **columnp,
1740                        char **keyp, char **valuep)
1741 {
1742     const char *p = arg;
1743     char *error;
1744
1745     assert(columnp || keyp);
1746     if (keyp) {
1747         *keyp = NULL;
1748     }
1749     if (valuep) {
1750         *valuep = NULL;
1751     }
1752
1753     /* Parse column name. */
1754     if (columnp) {
1755         char *column_name;
1756
1757         error = ovsdb_token_parse(&p, &column_name);
1758         if (error) {
1759             goto error;
1760         }
1761         if (column_name[0] == '\0') {
1762             free(column_name);
1763             error = xasprintf("%s: missing column name", arg);
1764             goto error;
1765         }
1766         error = get_column(table, column_name, columnp);
1767         if (error) {
1768             goto error;
1769         }
1770         free(column_name);
1771     }
1772
1773     /* Parse key string. */
1774     if (*p == ':' || !columnp) {
1775         if (columnp) {
1776             p++;
1777         } else if (!keyp) {
1778             error = xasprintf("%s: key not accepted here", arg);
1779             goto error;
1780         }
1781         error = ovsdb_token_parse(&p, keyp);
1782         if (error) {
1783             goto error;
1784         }
1785     } else if (keyp) {
1786         *keyp = NULL;
1787     }
1788
1789     /* Parse value string. */
1790     if (*p == '=') {
1791         if (!valuep) {
1792             error = xasprintf("%s: value not accepted here", arg);
1793             goto error;
1794         }
1795         *valuep = xstrdup(p + 1);
1796     } else {
1797         if (valuep) {
1798             *valuep = NULL;
1799         }
1800         if (*p != '\0') {
1801             error = xasprintf("%s: trailing garbage in argument at offset %td",
1802                               arg, p - arg);
1803             goto error;
1804         }
1805     }
1806     return NULL;
1807
1808 error:
1809     if (columnp) {
1810         *columnp = NULL;
1811     }
1812     if (keyp) {
1813         free(*keyp);
1814         *keyp = NULL;
1815     }
1816     if (valuep) {
1817         free(*valuep);
1818         *valuep = NULL;
1819     }
1820     return error;
1821 }
1822
1823 static void
1824 cmd_get(struct vsctl_context *ctx)
1825 {
1826     const char *table_name = ctx->argv[1];
1827     const char *record_id = ctx->argv[2];
1828     const struct vsctl_table_class *table;
1829     const struct ovsdb_idl_row *row;
1830     struct ds *out = &ctx->output;
1831     int i;
1832
1833     table = get_table(table_name);
1834     row = must_get_row(ctx, table, record_id);
1835     for (i = 3; i < ctx->argc; i++) {
1836         const struct vsctl_column *column;
1837         struct ovsdb_datum datum;
1838         char *key_string;
1839
1840         die_if_error(parse_column_key_value(ctx->argv[i], table,
1841                                             &column, &key_string, NULL));
1842
1843         ovsdb_idl_txn_read(row, column->idl, &datum);
1844         if (key_string) {
1845             union ovsdb_atom key;
1846             unsigned int idx;
1847
1848             if (column->idl->type.value_type == OVSDB_TYPE_VOID) {
1849                 ovs_fatal(0, "cannot specify key to get for non-map column %s",
1850                           column->idl->name);
1851             }
1852
1853             die_if_error(ovsdb_atom_from_string(&key,
1854                                                 column->idl->type.key_type,
1855                                                 key_string));
1856
1857             idx = ovsdb_datum_find_key(&datum, &key,
1858                                        column->idl->type.key_type);
1859             if (idx == UINT_MAX) {
1860                 ovs_fatal(0, "no key %s in %s record \"%s\" column %s",
1861                           key_string, table_name, record_id,
1862                           column->idl->name);
1863
1864             }
1865             ovsdb_atom_to_string(&datum.values[idx],
1866                                  column->idl->type.value_type, out);
1867
1868             ovsdb_atom_destroy(&key, column->idl->type.key_type);
1869         } else {
1870             ovsdb_datum_to_string(&datum, &column->idl->type, out);
1871         }
1872         ds_put_char(out, '\n');
1873         ovsdb_datum_destroy(&datum, &column->idl->type);
1874
1875         free(key_string);
1876     }
1877 }
1878
1879 static void
1880 list_record(const struct vsctl_table_class *table,
1881             const struct ovsdb_idl_row *row, struct ds *out)
1882 {
1883     const struct vsctl_column *column;
1884
1885     ds_put_format(out, "%-20s (RO): "UUID_FMT"\n", "_uuid",
1886                   UUID_ARGS(&row->uuid));
1887     for (column = table->columns; column->idl; column++) {
1888         struct ovsdb_datum datum;
1889
1890         if (column->flags & VSCF_HIDDEN) {
1891             continue;
1892         }
1893
1894         ovsdb_idl_txn_read(row, column->idl, &datum);
1895
1896         ds_put_format(out, "%-20s (%s): ", column->idl->name,
1897                       column->flags & VSCF_READONLY ? "RO" : "RW");
1898         ovsdb_datum_to_string(&datum, &column->idl->type, out);
1899         ds_put_char(out, '\n');
1900
1901         ovsdb_datum_destroy(&datum, &column->idl->type);
1902     }
1903 }
1904
1905 static void
1906 cmd_list(struct vsctl_context *ctx)
1907 {
1908     const char *table_name = ctx->argv[1];
1909     const struct vsctl_table_class *table;
1910     struct ds *out = &ctx->output;
1911     int i;
1912
1913     table = get_table(table_name);
1914     if (ctx->argc > 2) {
1915         for (i = 2; i < ctx->argc; i++) {
1916             if (i > 2) {
1917                 ds_put_char(out, '\n');
1918             }
1919             list_record(table, must_get_row(ctx, table, ctx->argv[i]), out);
1920         }
1921     } else {
1922         const struct ovsdb_idl_row *row;
1923         bool first;
1924
1925         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
1926              row != NULL;
1927              row = ovsdb_idl_next_row(row), first = false) {
1928             if (!first) {
1929                 ds_put_char(out, '\n');
1930             }
1931             list_record(table, row, out);
1932         }
1933     }
1934 }
1935
1936 static void
1937 check_string_constraint(const struct ovsdb_datum *datum,
1938                         const char *constraint)
1939 {
1940     unsigned int i;
1941     char *regex;
1942     regex_t re;
1943     int retval;
1944
1945     regex = xasprintf("^%s$", constraint);
1946     retval = regcomp(&re, regex, REG_NOSUB | REG_EXTENDED);
1947     if (retval) {
1948         size_t length = regerror(retval, &re, NULL, 0);
1949         char *buffer = xmalloc(length);
1950         regerror(retval, &re, buffer, length);
1951         ovs_fatal(0, "internal error compiling regular expression %s: %s",
1952                   regex, buffer);
1953     }
1954
1955     for (i = 0; i < datum->n; i++) {
1956         const char *key = datum->keys[i].string;
1957         if (regexec(&re, key, 0, NULL, 0)) {
1958             ovs_fatal(0, "%s is not valid (it does not match %s)", key, regex);
1959         }
1960     }
1961     free(regex);
1962     regfree(&re);
1963 }
1964
1965 static void
1966 check_integer_constraint(const struct ovsdb_datum *datum,
1967                          const char *constraint)
1968 {
1969     int64_t min, max;
1970     unsigned int i;
1971     int n = -1;
1972
1973     sscanf(constraint, "[%"SCNd64",%"SCNd64"]%n", &min, &max, &n);
1974     if (n == -1) {
1975         sscanf(constraint, "[%"SCNd64",]%n", &min, &n);
1976         if (n == -1) {
1977             sscanf(constraint, "[,%"SCNd64"]%n", &max, &n);
1978             if (n == -1) {
1979                 VLOG_DBG("internal error: bad integer contraint \"%s\"",
1980                          constraint);
1981                 return;
1982             } else {
1983                 min = INT64_MIN;
1984             }
1985         } else {
1986             max = INT64_MAX;
1987         }
1988     }
1989
1990     for (i = 0; i < datum->n; i++) {
1991         int64_t value = datum->keys[i].integer;
1992         if (value < min || value > max) {
1993             if (max == INT64_MAX) {
1994                 ovs_fatal(0, "%"PRId64" is less than the minimum "
1995                           "allowed value %"PRId64, value, min);
1996             } else if (min == INT64_MIN) {
1997                 ovs_fatal(0, "%"PRId64" is greater than the maximum "
1998                           "allowed value %"PRId64, value, max);
1999             } else {
2000                 ovs_fatal(0, "%"PRId64" is outside the valid range %"PRId64" "
2001                           "to %"PRId64" (inclusive)", value, min, max);
2002             }
2003         }
2004     }
2005 }
2006
2007 static void
2008 check_constraint(const struct ovsdb_datum *datum,
2009                  const struct ovsdb_type *type, const char *constraint)
2010 {
2011     if (constraint && datum->n) {
2012         if (type->key_type == OVSDB_TYPE_STRING) {
2013             check_string_constraint(datum, constraint);
2014         } else if (type->key_type == OVSDB_TYPE_INTEGER) {
2015             check_integer_constraint(datum, constraint);
2016         }
2017     }
2018 }
2019
2020 static void
2021 set_column(const struct vsctl_table_class *table,
2022            const struct ovsdb_idl_row *row,
2023            const char *arg, bool force)
2024 {
2025     const struct vsctl_column *column;
2026     char *key_string, *value_string;
2027     char *error;
2028
2029     error = parse_column_key_value(arg, table, &column, &key_string,
2030                                    &value_string);
2031     die_if_error(error);
2032     if (column->flags & VSCF_READONLY && !force) {
2033         ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2034                   arg, column->idl->name, table->class->name);
2035     }
2036     if (!value_string) {
2037         ovs_fatal(0, "%s: missing value", arg);
2038     }
2039
2040     if (key_string) {
2041         union ovsdb_atom key, value;
2042         struct ovsdb_datum old, new;
2043
2044         if (column->idl->type.value_type == OVSDB_TYPE_VOID) {
2045             ovs_fatal(0, "cannot specify key to set for non-map column %s",
2046                       column->idl->name);
2047         }
2048
2049         die_if_error(ovsdb_atom_from_string(&key,
2050                                             column->idl->type.key_type,
2051                                             key_string));
2052         die_if_error(ovsdb_atom_from_string(&value,
2053                                             column->idl->type.value_type,
2054                                             value_string));
2055
2056         ovsdb_datum_init_empty(&new);
2057         ovsdb_datum_add_unsafe(&new, &key, &value, &column->idl->type);
2058
2059         ovsdb_idl_txn_read(row, column->idl, &old);
2060         ovsdb_datum_union(&old, &new, &column->idl->type, true);
2061         ovsdb_idl_txn_write(row, column->idl, &old);
2062
2063         ovsdb_datum_destroy(&new, &column->idl->type);
2064     } else {
2065         struct ovsdb_datum datum;
2066
2067         die_if_error(ovsdb_datum_from_string(&datum, &column->idl->type,
2068                                              value_string));
2069         if (!force) {
2070             check_constraint(&datum, &column->idl->type,
2071                              column->constraint);
2072         }
2073         ovsdb_idl_txn_write(row, column->idl, &datum);
2074     }
2075
2076     free(key_string);
2077 }
2078
2079 static void
2080 cmd_set(struct vsctl_context *ctx)
2081 {
2082     bool force = shash_find(&ctx->options, "--force");
2083     const char *table_name = ctx->argv[1];
2084     const char *record_id = ctx->argv[2];
2085     const struct vsctl_table_class *table;
2086     const struct ovsdb_idl_row *row;
2087     int i;
2088
2089     table = get_table(table_name);
2090     row = must_get_row(ctx, table, record_id);
2091     for (i = 3; i < ctx->argc; i++) {
2092         set_column(table, row, ctx->argv[i], force);
2093     }
2094 }
2095
2096 static void
2097 cmd_add(struct vsctl_context *ctx)
2098 {
2099     bool force = shash_find(&ctx->options, "--force");
2100     const char *table_name = ctx->argv[1];
2101     const char *record_id = ctx->argv[2];
2102     const char *column_name = ctx->argv[3];
2103     const struct vsctl_table_class *table;
2104     const struct vsctl_column *column;
2105     const struct ovsdb_idl_row *row;
2106     const struct ovsdb_type *type;
2107     struct ovsdb_datum old;
2108     int i;
2109
2110     table = get_table(table_name);
2111     row = must_get_row(ctx, table, record_id);
2112     die_if_error(get_column(table, column_name, &column));
2113     type = &column->idl->type;
2114     ovsdb_idl_txn_read(row, column->idl, &old);
2115     for (i = 4; i < ctx->argc; i++) {
2116         struct ovsdb_type add_type;
2117         struct ovsdb_datum add;
2118
2119         if (column->flags & VSCF_READONLY && !force) {
2120             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2121                       ctx->argv[i], column->idl->name, table_name);
2122         }
2123
2124         add_type = *type;
2125         add_type.n_min = 1;
2126         add_type.n_max = UINT_MAX;
2127         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i]));
2128         ovsdb_datum_union(&old, &add, type, false);
2129         ovsdb_datum_destroy(&add, type);
2130     }
2131     if (old.n > type->n_max) {
2132         ovs_fatal(0, "\"add\" operation would put %u %s in column %s of "
2133                   "table %s but at most %u are allowed",
2134                   old.n,
2135                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2136                   column->idl->name, table_name, type->n_max);
2137     }
2138     ovsdb_idl_txn_write(row, column->idl, &old);
2139 }
2140
2141 static void
2142 cmd_remove(struct vsctl_context *ctx)
2143 {
2144     bool force = shash_find(&ctx->options, "--force");
2145     const char *table_name = ctx->argv[1];
2146     const char *record_id = ctx->argv[2];
2147     const char *column_name = ctx->argv[3];
2148     const struct vsctl_table_class *table;
2149     const struct vsctl_column *column;
2150     const struct ovsdb_idl_row *row;
2151     const struct ovsdb_type *type;
2152     struct ovsdb_datum old;
2153     int i;
2154
2155     table = get_table(table_name);
2156     row = must_get_row(ctx, table, record_id);
2157     die_if_error(get_column(table, column_name, &column));
2158     type = &column->idl->type;
2159     ovsdb_idl_txn_read(row, column->idl, &old);
2160     for (i = 4; i < ctx->argc; i++) {
2161         struct ovsdb_type rm_type;
2162         struct ovsdb_datum rm;
2163         char *error;
2164
2165         if (column->flags & VSCF_READONLY && !force) {
2166             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2167                       ctx->argv[i], column->idl->name, table_name);
2168         }
2169
2170         rm_type = *type;
2171         rm_type.n_min = 1;
2172         rm_type.n_max = UINT_MAX;
2173         error = ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]);
2174         if (error && ovsdb_type_is_map(&rm_type)) {
2175             free(error);
2176             rm_type.value_type = OVSDB_TYPE_VOID;
2177             die_if_error(ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]));
2178         }
2179         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
2180         ovsdb_datum_destroy(&rm, &rm_type);
2181     }
2182     if (old.n < type->n_min) {
2183         ovs_fatal(0, "\"remove\" operation would put %u %s in column %s of "
2184                   "table %s but at least %u are required",
2185                   old.n,
2186                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2187                   column->idl->name, table_name, type->n_min);
2188     }
2189     ovsdb_idl_txn_write(row, column->idl, &old);
2190 }
2191
2192 static void
2193 cmd_clear(struct vsctl_context *ctx)
2194 {
2195     bool force = shash_find(&ctx->options, "--force");
2196     const char *table_name = ctx->argv[1];
2197     const char *record_id = ctx->argv[2];
2198     const struct vsctl_table_class *table;
2199     const struct ovsdb_idl_row *row;
2200     int i;
2201
2202     table = get_table(table_name);
2203     row = must_get_row(ctx, table, record_id);
2204     for (i = 3; i < ctx->argc; i++) {
2205         const struct vsctl_column *column;
2206         const struct ovsdb_type *type;
2207         struct ovsdb_datum datum;
2208
2209         die_if_error(get_column(table, ctx->argv[i], &column));
2210
2211         type = &column->idl->type;
2212         if (column->flags & VSCF_READONLY && !force) {
2213             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2214                       ctx->argv[i], column->idl->name, table_name);
2215         } else if (type->n_min > 0) {
2216             ovs_fatal(0, "\"clear\" operation cannot be applied to column %s "
2217                       "of table %s, which is not allowed to be empty",
2218                       column->idl->name, table_name);
2219         }
2220
2221         ovsdb_datum_init_empty(&datum);
2222         ovsdb_idl_txn_write(row, column->idl, &datum);
2223     }
2224 }
2225
2226 static void
2227 cmd_create(struct vsctl_context *ctx)
2228 {
2229     bool force = shash_find(&ctx->options, "--force");
2230     const char *table_name = ctx->argv[1];
2231     const struct vsctl_table_class *table;
2232     const struct ovsdb_idl_row *row;
2233     int i;
2234
2235     if (!force) {
2236         ovs_fatal(0, "\"create\" requires --force");
2237     }
2238
2239     table = get_table(table_name);
2240     row = ovsdb_idl_txn_insert(txn_from_openvswitch(ctx->ovs), table->class);
2241     for (i = 2; i < ctx->argc; i++) {
2242         set_column(table, row, ctx->argv[i], force);
2243     }
2244 }
2245
2246 static void
2247 cmd_destroy(struct vsctl_context *ctx)
2248 {
2249     bool force = shash_find(&ctx->options, "--force");
2250     bool must_exist = !shash_find(&ctx->options, "--if-exists");
2251     const char *table_name = ctx->argv[1];
2252     const struct vsctl_table_class *table;
2253     int i;
2254
2255     if (!force) {
2256         ovs_fatal(0, "\"destroy\" requires --force");
2257     }
2258
2259     table = get_table(table_name);
2260     for (i = 1; i < ctx->argc; i++) {
2261         const struct ovsdb_idl_row *row;
2262
2263         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
2264         if (row) {
2265             ovsdb_idl_txn_delete(row);
2266         }
2267     }
2268 }
2269 \f
2270 typedef void vsctl_handler_func(struct vsctl_context *);
2271
2272 struct vsctl_command {
2273     const char *name;
2274     int min_args;
2275     int max_args;
2276     vsctl_handler_func *handler;
2277     const char *options;
2278 };
2279
2280 static void run_vsctl_command(int argc, char *argv[],
2281                               const struct ovsrec_open_vswitch *,
2282                               struct ovsdb_idl *, struct ds *output);
2283
2284 static struct json *
2285 where_uuid_equals(const struct uuid *uuid)
2286 {
2287     return
2288         json_array_create_1(
2289             json_array_create_3(
2290                 json_string_create("_uuid"),
2291                 json_string_create("=="),
2292                 json_array_create_2(
2293                     json_string_create("uuid"),
2294                     json_string_create_nocopy(
2295                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
2296 }
2297
2298 static void
2299 do_vsctl(int argc, char *argv[], struct ovsdb_idl *idl)
2300 {
2301     struct ovsdb_idl_txn *txn;
2302     const struct ovsrec_open_vswitch *ovs;
2303     enum ovsdb_idl_txn_status status;
2304     struct ds comment, *output;
2305     int64_t next_cfg = 0;
2306     int n_output;
2307     int i, start;
2308
2309     txn = ovsdb_idl_txn_create(idl);
2310     if (dry_run) {
2311         ovsdb_idl_txn_set_dry_run(txn);
2312     }
2313
2314     ds_init(&comment);
2315     ds_put_cstr(&comment, "ovs-vsctl:");
2316     for (i = 0; i < argc; i++) {
2317         ds_put_format(&comment, " %s", argv[i]);
2318     }
2319     ovsdb_idl_txn_add_comment(txn, ds_cstr(&comment));
2320     ds_destroy(&comment);
2321
2322     ovs = ovsrec_open_vswitch_first(idl);
2323     if (!ovs) {
2324         /* XXX add verification that table is empty */
2325         ovs = ovsrec_open_vswitch_insert(txn);
2326     }
2327
2328     if (wait_for_reload) {
2329         struct json *where = where_uuid_equals(&ovs->header_.uuid);
2330         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
2331         json_destroy(where);
2332     }
2333
2334     output = xmalloc(argc * sizeof *output);
2335     n_output = 0;
2336     for (start = i = 0; i <= argc; i++) {
2337         if (i == argc || !strcmp(argv[i], "--")) {
2338             if (i > start) {
2339                 ds_init(&output[n_output]);
2340                 run_vsctl_command(i - start, &argv[start], ovs, idl,
2341                                   &output[n_output++]);
2342             }
2343             start = i + 1;
2344         }
2345     }
2346
2347     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
2348         ovsdb_idl_run(idl);
2349         ovsdb_idl_wait(idl);
2350         ovsdb_idl_txn_wait(txn);
2351         poll_block();
2352     }
2353     if (wait_for_reload && status == TXN_SUCCESS) {
2354         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
2355     }
2356     ovsdb_idl_txn_destroy(txn);
2357
2358     switch (status) {
2359     case TXN_INCOMPLETE:
2360         NOT_REACHED();
2361
2362     case TXN_ABORTED:
2363         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2364         vsctl_fatal("transaction aborted");
2365
2366     case TXN_UNCHANGED:
2367     case TXN_SUCCESS:
2368         break;
2369
2370     case TXN_TRY_AGAIN:
2371         for (i = 0; i < n_output; i++) {
2372             ds_destroy(&output[i]);
2373         }
2374         return;
2375
2376     case TXN_ERROR:
2377         vsctl_fatal("transaction error");
2378
2379     default:
2380         NOT_REACHED();
2381     }
2382
2383     for (i = 0; i < n_output; i++) {
2384         struct ds *ds = &output[i];
2385         if (oneline) {
2386             size_t j;
2387
2388             ds_chomp(ds, '\n');
2389             for (j = 0; j < ds->length; j++) {
2390                 int c = ds->string[j];
2391                 switch (c) {
2392                 case '\n':
2393                     fputs("\\n", stdout);
2394                     break;
2395
2396                 case '\\':
2397                     fputs("\\\\", stdout);
2398                     break;
2399
2400                 default:
2401                     putchar(c);
2402                 }
2403             }
2404             putchar('\n');
2405         } else {
2406             fputs(ds_cstr(ds), stdout);
2407         }
2408     }
2409
2410     if (wait_for_reload && status != TXN_UNCHANGED) {
2411         for (;;) {
2412             const struct ovsrec_open_vswitch *ovs;
2413
2414             ovsdb_idl_run(idl);
2415             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
2416                 if (ovs->cur_cfg >= next_cfg) {
2417                     goto done;
2418                 }
2419             }
2420             ovsdb_idl_wait(idl);
2421             poll_block();
2422         }
2423     done: ;
2424     }
2425
2426     exit(EXIT_SUCCESS);
2427 }
2428
2429 static vsctl_handler_func *
2430 get_vsctl_handler(int argc, char *argv[], struct vsctl_context *ctx)
2431 {
2432     static const struct vsctl_command all_commands[] = {
2433         /* Open vSwitch commands. */
2434         {"init", 0, 0, cmd_init, ""},
2435
2436         /* Bridge commands. */
2437         {"add-br", 1, 3, cmd_add_br, ""},
2438         {"del-br", 1, 1, cmd_del_br, "--if-exists"},
2439         {"list-br", 0, 0, cmd_list_br, ""},
2440         {"br-exists", 1, 1, cmd_br_exists, ""},
2441         {"br-to-vlan", 1, 1, cmd_br_to_vlan, ""},
2442         {"br-to-parent", 1, 1, cmd_br_to_parent, ""},
2443         {"br-set-external-id", 2, 3, cmd_br_set_external_id, ""},
2444         {"br-get-external-id", 1, 2, cmd_br_get_external_id, ""},
2445
2446         /* Port commands. */
2447         {"list-ports", 1, 1, cmd_list_ports, ""},
2448         {"add-port", 2, 2, cmd_add_port, ""},
2449         {"add-bond", 4, INT_MAX, cmd_add_bond, "--fake-iface"},
2450         {"del-port", 1, 2, cmd_del_port, "--if-exists"},
2451         {"port-to-br", 1, 1, cmd_port_to_br, ""},
2452
2453         /* Interface commands. */
2454         {"list-ifaces", 1, 1, cmd_list_ifaces, ""},
2455         {"iface-to-br", 1, 1, cmd_iface_to_br, ""},
2456
2457         /* Controller commands. */
2458         {"get-controller", 0, 1, cmd_get_controller, ""},
2459         {"del-controller", 0, 1, cmd_del_controller, ""},
2460         {"set-controller", 1, 2, cmd_set_controller, ""},
2461         {"get-fail-mode", 0, 1, cmd_get_fail_mode, ""},
2462         {"del-fail-mode", 0, 1, cmd_del_fail_mode, ""},
2463         {"set-fail-mode", 1, 2, cmd_set_fail_mode, ""},
2464
2465         /* SSL commands. */
2466         {"get-ssl", 0, 0, cmd_get_ssl, ""},
2467         {"del-ssl", 0, 0, cmd_del_ssl, ""},
2468         {"set-ssl", 3, 3, cmd_set_ssl, "--bootstrap"},
2469
2470         /* Parameter commands. */
2471         {"get", 3, INT_MAX, cmd_get, ""},
2472         {"list", 1, INT_MAX, cmd_list, ""},
2473         {"set", 3, INT_MAX, cmd_set, "--force"},
2474         {"add", 4, INT_MAX, cmd_add, "--force"},
2475         {"remove", 4, INT_MAX, cmd_remove, "--force"},
2476         {"clear", 3, INT_MAX, cmd_clear, "--force"},
2477         {"create", 2, INT_MAX, cmd_create, "--force"},
2478         {"destroy", 1, INT_MAX, cmd_destroy, "--force,--if-exists"},
2479     };
2480
2481     const struct vsctl_command *p;
2482     int i;
2483
2484     shash_init(&ctx->options);
2485     for (i = 0; i < argc; i++) {
2486         if (argv[i][0] != '-') {
2487             break;
2488         }
2489         if (!shash_add_once(&ctx->options, argv[i], NULL)) {
2490             vsctl_fatal("'%s' option specified multiple times", argv[i]);
2491         }
2492     }
2493     if (i == argc) {
2494         vsctl_fatal("missing command name");
2495     }
2496
2497     for (p = all_commands; p < &all_commands[ARRAY_SIZE(all_commands)]; p++) {
2498         if (!strcmp(p->name, argv[i])) {
2499             struct shash_node *node;
2500             int n_arg;
2501
2502             SHASH_FOR_EACH (node, &ctx->options) {
2503                 const char *s = strstr(p->options, node->name);
2504                 int end = s ? s[strlen(node->name)] : EOF;
2505                 if (end != ',' && end != ' ' && end != '\0') {
2506                     vsctl_fatal("'%s' command has no '%s' option",
2507                                 argv[i], node->name);
2508                 }
2509             }
2510
2511             n_arg = argc - i - 1;
2512             if (n_arg < p->min_args) {
2513                 vsctl_fatal("'%s' command requires at least %d arguments",
2514                             p->name, p->min_args);
2515             } else if (n_arg > p->max_args) {
2516                 vsctl_fatal("'%s' command takes at most %d arguments",
2517                             p->name, p->max_args);
2518             } else {
2519                 ctx->argc = n_arg + 1;
2520                 ctx->argv = &argv[i];
2521                 return p->handler;
2522             }
2523         }
2524     }
2525
2526     vsctl_fatal("unknown command '%s'; use --help for help", argv[i]);
2527 }
2528
2529 static void
2530 check_vsctl_command(int argc, char *argv[])
2531 {
2532     struct vsctl_context ctx;
2533
2534     get_vsctl_handler(argc, argv, &ctx);
2535     shash_destroy(&ctx.options);
2536 }
2537
2538 static void
2539 run_vsctl_command(int argc, char *argv[],
2540                   const struct ovsrec_open_vswitch *ovs,
2541                   struct ovsdb_idl *idl, struct ds *output)
2542 {
2543     vsctl_handler_func *function;
2544     struct vsctl_context ctx;
2545
2546     function = get_vsctl_handler(argc, argv, &ctx);
2547     ctx.ovs = ovs;
2548     ctx.idl = idl;
2549     ds_init(&ctx.output);
2550     function(&ctx);
2551     *output = ctx.output;
2552     shash_destroy(&ctx.options);
2553 }