07d9ae2ca887e6eebd693bcfe1bd5144181c51b2
[openvswitch] / 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_datapath_type, VSCF_READONLY, NULL},
1398     {&ovsrec_bridge_col_name, VSCF_READONLY, NULL},
1399     {&ovsrec_bridge_col_mirrors, VSCF_READONLY, NULL},
1400     {&ovsrec_bridge_col_other_config, 0, NULL},
1401     {&ovsrec_bridge_col_flood_vlans, 0, "[1,4095]"},
1402     {&ovsrec_bridge_col_controller, VSCF_READONLY, NULL},
1403     {&ovsrec_bridge_col_netflow, VSCF_READONLY, NULL},
1404     {&ovsrec_bridge_col_external_ids, 0, NULL},
1405     {&ovsrec_bridge_col_ports, VSCF_READONLY, NULL},
1406     {NULL, 0, NULL},
1407 };
1408
1409 static const struct vsctl_column controller_columns[] = {
1410     {&ovsrec_controller_col_connection_mode, 0, "in-band|out-of-band"},
1411     {&ovsrec_controller_col_controller_burst_limit, 0, "[25,]"},
1412     {&ovsrec_controller_col_controller_rate_limit, 0, "[100,]"},
1413     {&ovsrec_controller_col_discover_accept_regex, 0, NULL},
1414     {&ovsrec_controller_col_discover_update_resolv_conf, 0, NULL},
1415     {&ovsrec_controller_col_fail_mode, 0, "standalone|secure"},
1416     {&ovsrec_controller_col_inactivity_probe, 0, "[5000,]"},
1417     {&ovsrec_controller_col_local_gateway, 0, IP_RE},
1418     {&ovsrec_controller_col_local_ip, 0, IP_RE},
1419     {&ovsrec_controller_col_local_netmask, 0, NETMASK_RE},
1420     {&ovsrec_controller_col_max_backoff, 0, "[1000,]"},
1421     {&ovsrec_controller_col_target, 0, NULL},
1422     {NULL, 0, NULL},
1423 };
1424
1425 static const struct vsctl_column interface_columns[] = {
1426     {&ovsrec_interface_col_external_ids, 0, NULL},
1427     {&ovsrec_interface_col_ingress_policing_burst, 0, "[10,]"},
1428     {&ovsrec_interface_col_ingress_policing_rate, 0, "[100,]"},
1429     {&ovsrec_interface_col_mac, 0, MAC_RE},
1430     {&ovsrec_interface_col_name, VSCF_READONLY, NULL},
1431     {&ovsrec_interface_col_ofport, VSCF_READONLY, NULL},
1432     {&ovsrec_interface_col_options, 0, NULL},
1433     {&ovsrec_interface_col_type, VSCF_READONLY, NULL},
1434     {NULL, 0, NULL},
1435 };
1436
1437 static const struct vsctl_column mirror_columns[] = {
1438     {&ovsrec_mirror_col_name, VSCF_READONLY, NULL},
1439     {&ovsrec_mirror_col_output_port, 0, "Port"},
1440     {&ovsrec_mirror_col_output_vlan, 0, "[1,4095]"},
1441     {&ovsrec_mirror_col_select_dst_port, 0, "Port"},
1442     {&ovsrec_mirror_col_select_src_port, 0, "Port"},
1443     {&ovsrec_mirror_col_select_vlan, 0, "[1,4095]"},
1444     {NULL, 0, NULL},
1445 };
1446
1447 static const struct vsctl_column netflow_columns[] = {
1448     {&ovsrec_netflow_col_active_timeout, 0, "[-1,]"},
1449     {&ovsrec_netflow_col_add_id_to_interface, 0, NULL},
1450     {&ovsrec_netflow_col_targets, 0, IP_RE":"PORT_RE},
1451     {&ovsrec_netflow_col_engine_type, 0, "[0,255]"},
1452     {&ovsrec_netflow_col_engine_id, 0, "[0,255]"},
1453     {NULL, 0, NULL},
1454 };
1455
1456 static const struct vsctl_column open_vswitch_columns[] = {
1457     {&ovsrec_open_vswitch_col_bridges, VSCF_READONLY, NULL},
1458     {&ovsrec_open_vswitch_col_controller, VSCF_READONLY, NULL},
1459     {&ovsrec_open_vswitch_col_cur_cfg, VSCF_HIDDEN, NULL},
1460     {&ovsrec_open_vswitch_col_management_id, 0, "[0-9a-fA-F]{12}"},
1461     {&ovsrec_open_vswitch_col_managers, 0, "p?(ssl|tcp|unix):.*"},
1462     {&ovsrec_open_vswitch_col_next_cfg, VSCF_HIDDEN, NULL},
1463     {&ovsrec_open_vswitch_col_ssl, VSCF_READONLY, NULL},
1464     {NULL, 0, NULL},
1465 };
1466
1467 static const struct vsctl_column port_columns[] = {
1468     {&ovsrec_port_col_bond_updelay, 0, "[0,]"},
1469     {&ovsrec_port_col_bond_downdelay, 0, "[0,]"},
1470     {&ovsrec_port_col_bond_fake_iface, VSCF_READONLY, NULL},
1471     {&ovsrec_port_col_external_ids, 0, NULL},
1472     {&ovsrec_port_col_fake_bridge, VSCF_READONLY, NULL},
1473     {&ovsrec_port_col_interfaces, VSCF_READONLY, NULL},
1474     {&ovsrec_port_col_mac, 0, MAC_RE},
1475     {&ovsrec_port_col_name, VSCF_READONLY, NULL},
1476     {&ovsrec_port_col_other_config, 0, NULL},
1477     {&ovsrec_port_col_tag, 0, "[0,4095]"},
1478     {&ovsrec_port_col_trunks, 0, "[0,4095]"},
1479     {NULL, 0, NULL},
1480 };
1481
1482 static const struct vsctl_column ssl_columns[] = {
1483     {&ovsrec_ssl_col_bootstrap_ca_cert, 0, NULL},
1484     {&ovsrec_ssl_col_ca_cert, 0, NULL},
1485     {&ovsrec_ssl_col_certificate, 0, NULL},
1486     {&ovsrec_ssl_col_private_key, 0, NULL},
1487     {NULL, 0, NULL},
1488 };
1489
1490 struct vsctl_row_id {
1491     const struct ovsdb_idl_table_class *table;
1492     const struct ovsdb_idl_column *name_column;
1493     const struct ovsdb_idl_column *uuid_column;
1494 };
1495
1496 struct vsctl_table_class {
1497     struct ovsdb_idl_table_class *class;
1498     const struct vsctl_column *columns;
1499     struct vsctl_row_id row_ids[2];
1500 };
1501
1502 static const struct vsctl_table_class tables[] = {
1503     {&ovsrec_table_bridge, bridge_columns,
1504      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
1505       {NULL, NULL, NULL}}},
1506
1507     {&ovsrec_table_controller, controller_columns,
1508      {{&ovsrec_table_bridge,
1509        &ovsrec_bridge_col_name,
1510        &ovsrec_bridge_col_controller},
1511       {&ovsrec_table_open_vswitch,
1512        NULL,
1513        &ovsrec_open_vswitch_col_controller}}},
1514
1515     {&ovsrec_table_interface, interface_columns,
1516      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
1517       {NULL, NULL, NULL}}},
1518
1519     {&ovsrec_table_mirror, mirror_columns,
1520      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
1521       {NULL, NULL, NULL}}},
1522
1523     {&ovsrec_table_netflow, netflow_columns,
1524      {{&ovsrec_table_bridge,
1525        &ovsrec_bridge_col_name,
1526        &ovsrec_bridge_col_netflow},
1527       {NULL, NULL, NULL}}},
1528
1529     {&ovsrec_table_open_vswitch, open_vswitch_columns,
1530      {{&ovsrec_table_open_vswitch, NULL, NULL},
1531       {NULL, NULL, NULL}}},
1532
1533     {&ovsrec_table_port, port_columns,
1534      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
1535       {NULL, NULL, NULL}}},
1536
1537     {&ovsrec_table_ssl, ssl_columns,
1538      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
1539
1540     {NULL, NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1541 };
1542
1543 static void
1544 die_if_error(char *error)
1545 {
1546     if (error) {
1547         ovs_fatal(0, "%s", error);
1548     }
1549 }
1550
1551 static int
1552 to_lower_and_underscores(unsigned c)
1553 {
1554     return c == '-' ? '_' : tolower(c);
1555 }
1556
1557 static unsigned int
1558 score_partial_match(const char *name, const char *s)
1559 {
1560     int score;
1561
1562     if (!strcmp(name, s)) {
1563         return UINT_MAX;
1564     }
1565     for (score = 0; ; score++, name++, s++) {
1566         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
1567             break;
1568         } else if (*name == '\0') {
1569             return UINT_MAX - 1;
1570         }
1571     }
1572     return *s == '\0' ? score : 0;
1573 }
1574
1575 static const struct vsctl_table_class *
1576 get_table(const char *table_name)
1577 {
1578     const struct vsctl_table_class *table;
1579     const struct vsctl_table_class *best_match = NULL;
1580     unsigned int best_score = 0;
1581
1582     for (table = tables; table->class; table++) {
1583         unsigned int score = score_partial_match(table->class->name,
1584                                                  table_name);
1585         if (score > best_score) {
1586             best_match = table;
1587             best_score = score;
1588         } else if (score == best_score) {
1589             best_match = NULL;
1590         }
1591     }
1592     if (best_match) {
1593         return best_match;
1594     } else if (best_score) {
1595         ovs_fatal(0, "multiple table names match \"%s\"", table_name);
1596     } else {
1597         ovs_fatal(0, "unknown table \"%s\"", table_name);
1598     }
1599 }
1600
1601 static const struct ovsdb_idl_row *
1602 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
1603               const struct vsctl_row_id *id, const char *record_id)
1604 {
1605     const struct ovsdb_idl_row *referrer, *final;
1606
1607     if (!id->table) {
1608         return NULL;
1609     }
1610
1611     if (!id->name_column) {
1612         if (strcmp(record_id, ".")) {
1613             return NULL;
1614         }
1615         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
1616         if (!referrer || ovsdb_idl_next_row(referrer)) {
1617             return NULL;
1618         }
1619     } else {
1620         const struct ovsdb_idl_row *row;
1621         unsigned int best_score = 0;
1622
1623         /* It might make sense to relax this assertion. */
1624         assert(id->name_column->type.key_type == OVSDB_TYPE_STRING);
1625
1626         referrer = NULL;
1627         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
1628              row != NULL && best_score != UINT_MAX;
1629              row = ovsdb_idl_next_row(row))
1630         {
1631             struct ovsdb_datum name;
1632
1633             ovsdb_idl_txn_read(row, id->name_column, &name);
1634             if (name.n == 1) {
1635                 unsigned int score = score_partial_match(name.keys[0].string,
1636                                                          record_id);
1637                 if (score > best_score) {
1638                     referrer = row;
1639                     best_score = score;
1640                 } else if (score == best_score) {
1641                     referrer = NULL;
1642                 }
1643             }
1644             ovsdb_datum_destroy(&name, &id->name_column->type);
1645         }
1646     }
1647     if (!referrer) {
1648         return NULL;
1649     }
1650
1651     final = NULL;
1652     if (id->uuid_column) {
1653         struct ovsdb_datum uuid;
1654
1655         assert(id->uuid_column->type.key_type == OVSDB_TYPE_UUID);
1656         assert(id->uuid_column->type.value_type == OVSDB_TYPE_VOID);
1657
1658         ovsdb_idl_txn_read(referrer, id->uuid_column, &uuid);
1659         if (uuid.n == 1) {
1660             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
1661                                                &uuid.keys[0].uuid);
1662         }
1663         ovsdb_datum_destroy(&uuid, &id->uuid_column->type);
1664     } else {
1665         final = referrer;
1666     }
1667
1668     return final;
1669 }
1670
1671 static const struct ovsdb_idl_row *
1672 get_row(struct vsctl_context *ctx,
1673         const struct vsctl_table_class *table, const char *record_id)
1674 {
1675     const struct ovsdb_idl_row *row;
1676     struct uuid uuid;
1677
1678     if (uuid_from_string(&uuid, record_id)) {
1679         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
1680     } else {
1681         int i;
1682
1683         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
1684             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
1685             if (row) {
1686                 break;
1687             }
1688         }
1689     }
1690     return row;
1691 }
1692
1693 static const struct ovsdb_idl_row *
1694 must_get_row(struct vsctl_context *ctx,
1695              const struct vsctl_table_class *table, const char *record_id)
1696 {
1697     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
1698     if (!row) {
1699         ovs_fatal(0, "no row \"%s\" in table %s",
1700                   record_id, table->class->name);
1701     }
1702     return row;
1703 }
1704
1705 static char *
1706 get_column(const struct vsctl_table_class *table, const char *column_name,
1707            const struct vsctl_column **columnp)
1708 {
1709     const struct vsctl_column *column;
1710     const struct vsctl_column *best_match = NULL;
1711     unsigned int best_score = 0;
1712
1713     for (column = table->columns; column->idl; column++) {
1714         if (!(column->flags & VSCF_HIDDEN)) {
1715             unsigned int score = score_partial_match(column->idl->name,
1716                                                      column_name);
1717             if (score > best_score) {
1718                 best_match = column;
1719                 best_score = score;
1720             } else if (score == best_score) {
1721                 best_match = NULL;
1722             }
1723         }
1724     }
1725
1726     *columnp = best_match;
1727     if (best_match) {
1728         return NULL;
1729     } else if (best_score) {
1730         return xasprintf("%s contains more than one column whose name "
1731                          "matches \"%s\"", table->class->name, column_name);
1732     } else {
1733         return xasprintf("%s does not contain a column whose name matches "
1734                          "\"%s\"", table->class->name, column_name);
1735     }
1736 }
1737
1738 static char * WARN_UNUSED_RESULT
1739 parse_column_key_value(const char *arg, const struct vsctl_table_class *table,
1740                        const struct vsctl_column **columnp,
1741                        char **keyp, char **valuep)
1742 {
1743     const char *p = arg;
1744     char *error;
1745
1746     assert(columnp || keyp);
1747     if (keyp) {
1748         *keyp = NULL;
1749     }
1750     if (valuep) {
1751         *valuep = NULL;
1752     }
1753
1754     /* Parse column name. */
1755     if (columnp) {
1756         char *column_name;
1757
1758         error = ovsdb_token_parse(&p, &column_name);
1759         if (error) {
1760             goto error;
1761         }
1762         if (column_name[0] == '\0') {
1763             free(column_name);
1764             error = xasprintf("%s: missing column name", arg);
1765             goto error;
1766         }
1767         error = get_column(table, column_name, columnp);
1768         if (error) {
1769             goto error;
1770         }
1771         free(column_name);
1772     }
1773
1774     /* Parse key string. */
1775     if (*p == ':' || !columnp) {
1776         if (columnp) {
1777             p++;
1778         } else if (!keyp) {
1779             error = xasprintf("%s: key not accepted here", arg);
1780             goto error;
1781         }
1782         error = ovsdb_token_parse(&p, keyp);
1783         if (error) {
1784             goto error;
1785         }
1786     } else if (keyp) {
1787         *keyp = NULL;
1788     }
1789
1790     /* Parse value string. */
1791     if (*p == '=') {
1792         if (!valuep) {
1793             error = xasprintf("%s: value not accepted here", arg);
1794             goto error;
1795         }
1796         *valuep = xstrdup(p + 1);
1797     } else {
1798         if (valuep) {
1799             *valuep = NULL;
1800         }
1801         if (*p != '\0') {
1802             error = xasprintf("%s: trailing garbage in argument at offset %td",
1803                               arg, p - arg);
1804             goto error;
1805         }
1806     }
1807     return NULL;
1808
1809 error:
1810     if (columnp) {
1811         *columnp = NULL;
1812     }
1813     if (keyp) {
1814         free(*keyp);
1815         *keyp = NULL;
1816     }
1817     if (valuep) {
1818         free(*valuep);
1819         *valuep = NULL;
1820     }
1821     return error;
1822 }
1823
1824 static void
1825 cmd_get(struct vsctl_context *ctx)
1826 {
1827     const char *table_name = ctx->argv[1];
1828     const char *record_id = ctx->argv[2];
1829     const struct vsctl_table_class *table;
1830     const struct ovsdb_idl_row *row;
1831     struct ds *out = &ctx->output;
1832     int i;
1833
1834     table = get_table(table_name);
1835     row = must_get_row(ctx, table, record_id);
1836     for (i = 3; i < ctx->argc; i++) {
1837         const struct vsctl_column *column;
1838         struct ovsdb_datum datum;
1839         char *key_string;
1840
1841         die_if_error(parse_column_key_value(ctx->argv[i], table,
1842                                             &column, &key_string, NULL));
1843
1844         ovsdb_idl_txn_read(row, column->idl, &datum);
1845         if (key_string) {
1846             union ovsdb_atom key;
1847             unsigned int idx;
1848
1849             if (column->idl->type.value_type == OVSDB_TYPE_VOID) {
1850                 ovs_fatal(0, "cannot specify key to get for non-map column %s",
1851                           column->idl->name);
1852             }
1853
1854             die_if_error(ovsdb_atom_from_string(&key,
1855                                                 column->idl->type.key_type,
1856                                                 key_string));
1857
1858             idx = ovsdb_datum_find_key(&datum, &key,
1859                                        column->idl->type.key_type);
1860             if (idx == UINT_MAX) {
1861                 ovs_fatal(0, "no key %s in %s record \"%s\" column %s",
1862                           key_string, table_name, record_id,
1863                           column->idl->name);
1864
1865             }
1866             ovsdb_atom_to_string(&datum.values[idx],
1867                                  column->idl->type.value_type, out);
1868
1869             ovsdb_atom_destroy(&key, column->idl->type.key_type);
1870         } else {
1871             ovsdb_datum_to_string(&datum, &column->idl->type, out);
1872         }
1873         ds_put_char(out, '\n');
1874         ovsdb_datum_destroy(&datum, &column->idl->type);
1875
1876         free(key_string);
1877     }
1878 }
1879
1880 static void
1881 list_record(const struct vsctl_table_class *table,
1882             const struct ovsdb_idl_row *row, struct ds *out)
1883 {
1884     const struct vsctl_column *column;
1885
1886     ds_put_format(out, "%-20s (RO): "UUID_FMT"\n", "_uuid",
1887                   UUID_ARGS(&row->uuid));
1888     for (column = table->columns; column->idl; column++) {
1889         struct ovsdb_datum datum;
1890
1891         if (column->flags & VSCF_HIDDEN) {
1892             continue;
1893         }
1894
1895         ovsdb_idl_txn_read(row, column->idl, &datum);
1896
1897         ds_put_format(out, "%-20s (%s): ", column->idl->name,
1898                       column->flags & VSCF_READONLY ? "RO" : "RW");
1899         ovsdb_datum_to_string(&datum, &column->idl->type, out);
1900         ds_put_char(out, '\n');
1901
1902         ovsdb_datum_destroy(&datum, &column->idl->type);
1903     }
1904 }
1905
1906 static void
1907 cmd_list(struct vsctl_context *ctx)
1908 {
1909     const char *table_name = ctx->argv[1];
1910     const struct vsctl_table_class *table;
1911     struct ds *out = &ctx->output;
1912     int i;
1913
1914     table = get_table(table_name);
1915     if (ctx->argc > 2) {
1916         for (i = 2; i < ctx->argc; i++) {
1917             if (i > 2) {
1918                 ds_put_char(out, '\n');
1919             }
1920             list_record(table, must_get_row(ctx, table, ctx->argv[i]), out);
1921         }
1922     } else {
1923         const struct ovsdb_idl_row *row;
1924         bool first;
1925
1926         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
1927              row != NULL;
1928              row = ovsdb_idl_next_row(row), first = false) {
1929             if (!first) {
1930                 ds_put_char(out, '\n');
1931             }
1932             list_record(table, row, out);
1933         }
1934     }
1935 }
1936
1937 static void
1938 check_string_constraint(const struct ovsdb_datum *datum,
1939                         const char *constraint)
1940 {
1941     unsigned int i;
1942     char *regex;
1943     regex_t re;
1944     int retval;
1945
1946     regex = xasprintf("^%s$", constraint);
1947     retval = regcomp(&re, regex, REG_NOSUB | REG_EXTENDED);
1948     if (retval) {
1949         size_t length = regerror(retval, &re, NULL, 0);
1950         char *buffer = xmalloc(length);
1951         regerror(retval, &re, buffer, length);
1952         ovs_fatal(0, "internal error compiling regular expression %s: %s",
1953                   regex, buffer);
1954     }
1955
1956     for (i = 0; i < datum->n; i++) {
1957         const char *key = datum->keys[i].string;
1958         if (regexec(&re, key, 0, NULL, 0)) {
1959             ovs_fatal(0, "%s is not valid (it does not match %s)", key, regex);
1960         }
1961     }
1962     free(regex);
1963     regfree(&re);
1964 }
1965
1966 static void
1967 check_integer_constraint(const struct ovsdb_datum *datum,
1968                          const char *constraint)
1969 {
1970     int64_t min, max;
1971     unsigned int i;
1972     int n = -1;
1973
1974     sscanf(constraint, "[%"SCNd64",%"SCNd64"]%n", &min, &max, &n);
1975     if (n == -1) {
1976         sscanf(constraint, "[%"SCNd64",]%n", &min, &n);
1977         if (n == -1) {
1978             sscanf(constraint, "[,%"SCNd64"]%n", &max, &n);
1979             if (n == -1) {
1980                 VLOG_DBG("internal error: bad integer contraint \"%s\"",
1981                          constraint);
1982                 return;
1983             } else {
1984                 min = INT64_MIN;
1985             }
1986         } else {
1987             max = INT64_MAX;
1988         }
1989     }
1990
1991     for (i = 0; i < datum->n; i++) {
1992         int64_t value = datum->keys[i].integer;
1993         if (value < min || value > max) {
1994             if (max == INT64_MAX) {
1995                 ovs_fatal(0, "%"PRId64" is less than the minimum "
1996                           "allowed value %"PRId64, value, min);
1997             } else if (min == INT64_MIN) {
1998                 ovs_fatal(0, "%"PRId64" is greater than the maximum "
1999                           "allowed value %"PRId64, value, max);
2000             } else {
2001                 ovs_fatal(0, "%"PRId64" is outside the valid range %"PRId64" "
2002                           "to %"PRId64" (inclusive)", value, min, max);
2003             }
2004         }
2005     }
2006 }
2007
2008 static void
2009 check_constraint(const struct ovsdb_datum *datum,
2010                  const struct ovsdb_type *type, const char *constraint)
2011 {
2012     if (constraint && datum->n) {
2013         if (type->key_type == OVSDB_TYPE_STRING) {
2014             check_string_constraint(datum, constraint);
2015         } else if (type->key_type == OVSDB_TYPE_INTEGER) {
2016             check_integer_constraint(datum, constraint);
2017         }
2018     }
2019 }
2020
2021 static void
2022 set_column(const struct vsctl_table_class *table,
2023            const struct ovsdb_idl_row *row,
2024            const char *arg, bool force)
2025 {
2026     const struct vsctl_column *column;
2027     char *key_string, *value_string;
2028     char *error;
2029
2030     error = parse_column_key_value(arg, table, &column, &key_string,
2031                                    &value_string);
2032     die_if_error(error);
2033     if (column->flags & VSCF_READONLY && !force) {
2034         ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2035                   arg, column->idl->name, table->class->name);
2036     }
2037     if (!value_string) {
2038         ovs_fatal(0, "%s: missing value", arg);
2039     }
2040
2041     if (key_string) {
2042         union ovsdb_atom key, value;
2043         struct ovsdb_datum old, new;
2044
2045         if (column->idl->type.value_type == OVSDB_TYPE_VOID) {
2046             ovs_fatal(0, "cannot specify key to set for non-map column %s",
2047                       column->idl->name);
2048         }
2049
2050         die_if_error(ovsdb_atom_from_string(&key,
2051                                             column->idl->type.key_type,
2052                                             key_string));
2053         die_if_error(ovsdb_atom_from_string(&value,
2054                                             column->idl->type.value_type,
2055                                             value_string));
2056
2057         ovsdb_datum_init_empty(&new);
2058         ovsdb_datum_add_unsafe(&new, &key, &value, &column->idl->type);
2059
2060         ovsdb_idl_txn_read(row, column->idl, &old);
2061         ovsdb_datum_union(&old, &new, &column->idl->type, true);
2062         ovsdb_idl_txn_write(row, column->idl, &old);
2063
2064         ovsdb_datum_destroy(&new, &column->idl->type);
2065     } else {
2066         struct ovsdb_datum datum;
2067
2068         die_if_error(ovsdb_datum_from_string(&datum, &column->idl->type,
2069                                              value_string));
2070         if (!force) {
2071             check_constraint(&datum, &column->idl->type,
2072                              column->constraint);
2073         }
2074         ovsdb_idl_txn_write(row, column->idl, &datum);
2075     }
2076
2077     free(key_string);
2078 }
2079
2080 static void
2081 cmd_set(struct vsctl_context *ctx)
2082 {
2083     bool force = shash_find(&ctx->options, "--force");
2084     const char *table_name = ctx->argv[1];
2085     const char *record_id = ctx->argv[2];
2086     const struct vsctl_table_class *table;
2087     const struct ovsdb_idl_row *row;
2088     int i;
2089
2090     table = get_table(table_name);
2091     row = must_get_row(ctx, table, record_id);
2092     for (i = 3; i < ctx->argc; i++) {
2093         set_column(table, row, ctx->argv[i], force);
2094     }
2095 }
2096
2097 static void
2098 cmd_add(struct vsctl_context *ctx)
2099 {
2100     bool force = shash_find(&ctx->options, "--force");
2101     const char *table_name = ctx->argv[1];
2102     const char *record_id = ctx->argv[2];
2103     const char *column_name = ctx->argv[3];
2104     const struct vsctl_table_class *table;
2105     const struct vsctl_column *column;
2106     const struct ovsdb_idl_row *row;
2107     const struct ovsdb_type *type;
2108     struct ovsdb_datum old;
2109     int i;
2110
2111     table = get_table(table_name);
2112     row = must_get_row(ctx, table, record_id);
2113     die_if_error(get_column(table, column_name, &column));
2114     type = &column->idl->type;
2115     ovsdb_idl_txn_read(row, column->idl, &old);
2116     for (i = 4; i < ctx->argc; i++) {
2117         struct ovsdb_type add_type;
2118         struct ovsdb_datum add;
2119
2120         if (column->flags & VSCF_READONLY && !force) {
2121             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2122                       ctx->argv[i], column->idl->name, table_name);
2123         }
2124
2125         add_type = *type;
2126         add_type.n_min = 1;
2127         add_type.n_max = UINT_MAX;
2128         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i]));
2129         ovsdb_datum_union(&old, &add, type, false);
2130         ovsdb_datum_destroy(&add, type);
2131     }
2132     if (old.n > type->n_max) {
2133         ovs_fatal(0, "\"add\" operation would put %u %s in column %s of "
2134                   "table %s but at most %u are allowed",
2135                   old.n,
2136                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2137                   column->idl->name, table_name, type->n_max);
2138     }
2139     ovsdb_idl_txn_write(row, column->idl, &old);
2140 }
2141
2142 static void
2143 cmd_remove(struct vsctl_context *ctx)
2144 {
2145     bool force = shash_find(&ctx->options, "--force");
2146     const char *table_name = ctx->argv[1];
2147     const char *record_id = ctx->argv[2];
2148     const char *column_name = ctx->argv[3];
2149     const struct vsctl_table_class *table;
2150     const struct vsctl_column *column;
2151     const struct ovsdb_idl_row *row;
2152     const struct ovsdb_type *type;
2153     struct ovsdb_datum old;
2154     int i;
2155
2156     table = get_table(table_name);
2157     row = must_get_row(ctx, table, record_id);
2158     die_if_error(get_column(table, column_name, &column));
2159     type = &column->idl->type;
2160     ovsdb_idl_txn_read(row, column->idl, &old);
2161     for (i = 4; i < ctx->argc; i++) {
2162         struct ovsdb_type rm_type;
2163         struct ovsdb_datum rm;
2164         char *error;
2165
2166         if (column->flags & VSCF_READONLY && !force) {
2167             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2168                       ctx->argv[i], column->idl->name, table_name);
2169         }
2170
2171         rm_type = *type;
2172         rm_type.n_min = 1;
2173         rm_type.n_max = UINT_MAX;
2174         error = ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]);
2175         if (error && ovsdb_type_is_map(&rm_type)) {
2176             free(error);
2177             rm_type.value_type = OVSDB_TYPE_VOID;
2178             die_if_error(ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]));
2179         }
2180         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
2181         ovsdb_datum_destroy(&rm, &rm_type);
2182     }
2183     if (old.n < type->n_min) {
2184         ovs_fatal(0, "\"remove\" operation would put %u %s in column %s of "
2185                   "table %s but at least %u are required",
2186                   old.n,
2187                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2188                   column->idl->name, table_name, type->n_min);
2189     }
2190     ovsdb_idl_txn_write(row, column->idl, &old);
2191 }
2192
2193 static void
2194 cmd_clear(struct vsctl_context *ctx)
2195 {
2196     bool force = shash_find(&ctx->options, "--force");
2197     const char *table_name = ctx->argv[1];
2198     const char *record_id = ctx->argv[2];
2199     const struct vsctl_table_class *table;
2200     const struct ovsdb_idl_row *row;
2201     int i;
2202
2203     table = get_table(table_name);
2204     row = must_get_row(ctx, table, record_id);
2205     for (i = 3; i < ctx->argc; i++) {
2206         const struct vsctl_column *column;
2207         const struct ovsdb_type *type;
2208         struct ovsdb_datum datum;
2209
2210         die_if_error(get_column(table, ctx->argv[i], &column));
2211
2212         type = &column->idl->type;
2213         if (column->flags & VSCF_READONLY && !force) {
2214             ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2215                       ctx->argv[i], column->idl->name, table_name);
2216         } else if (type->n_min > 0) {
2217             ovs_fatal(0, "\"clear\" operation cannot be applied to column %s "
2218                       "of table %s, which is not allowed to be empty",
2219                       column->idl->name, table_name);
2220         }
2221
2222         ovsdb_datum_init_empty(&datum);
2223         ovsdb_idl_txn_write(row, column->idl, &datum);
2224     }
2225 }
2226
2227 static void
2228 cmd_create(struct vsctl_context *ctx)
2229 {
2230     bool force = shash_find(&ctx->options, "--force");
2231     const char *table_name = ctx->argv[1];
2232     const struct vsctl_table_class *table;
2233     const struct ovsdb_idl_row *row;
2234     int i;
2235
2236     if (!force) {
2237         ovs_fatal(0, "\"create\" requires --force");
2238     }
2239
2240     table = get_table(table_name);
2241     row = ovsdb_idl_txn_insert(txn_from_openvswitch(ctx->ovs), table->class);
2242     for (i = 2; i < ctx->argc; i++) {
2243         set_column(table, row, ctx->argv[i], force);
2244     }
2245 }
2246
2247 static void
2248 cmd_destroy(struct vsctl_context *ctx)
2249 {
2250     bool force = shash_find(&ctx->options, "--force");
2251     bool must_exist = !shash_find(&ctx->options, "--if-exists");
2252     const char *table_name = ctx->argv[1];
2253     const struct vsctl_table_class *table;
2254     int i;
2255
2256     if (!force) {
2257         ovs_fatal(0, "\"destroy\" requires --force");
2258     }
2259
2260     table = get_table(table_name);
2261     for (i = 1; i < ctx->argc; i++) {
2262         const struct ovsdb_idl_row *row;
2263
2264         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
2265         if (row) {
2266             ovsdb_idl_txn_delete(row);
2267         }
2268     }
2269 }
2270 \f
2271 typedef void vsctl_handler_func(struct vsctl_context *);
2272
2273 struct vsctl_command {
2274     const char *name;
2275     int min_args;
2276     int max_args;
2277     vsctl_handler_func *handler;
2278     const char *options;
2279 };
2280
2281 static void run_vsctl_command(int argc, char *argv[],
2282                               const struct ovsrec_open_vswitch *,
2283                               struct ovsdb_idl *, struct ds *output);
2284
2285 static struct json *
2286 where_uuid_equals(const struct uuid *uuid)
2287 {
2288     return
2289         json_array_create_1(
2290             json_array_create_3(
2291                 json_string_create("_uuid"),
2292                 json_string_create("=="),
2293                 json_array_create_2(
2294                     json_string_create("uuid"),
2295                     json_string_create_nocopy(
2296                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
2297 }
2298
2299 static void
2300 do_vsctl(int argc, char *argv[], struct ovsdb_idl *idl)
2301 {
2302     struct ovsdb_idl_txn *txn;
2303     const struct ovsrec_open_vswitch *ovs;
2304     enum ovsdb_idl_txn_status status;
2305     struct ds comment, *output;
2306     int64_t next_cfg = 0;
2307     int n_output;
2308     int i, start;
2309
2310     txn = ovsdb_idl_txn_create(idl);
2311     if (dry_run) {
2312         ovsdb_idl_txn_set_dry_run(txn);
2313     }
2314
2315     ds_init(&comment);
2316     ds_put_cstr(&comment, "ovs-vsctl:");
2317     for (i = 0; i < argc; i++) {
2318         ds_put_format(&comment, " %s", argv[i]);
2319     }
2320     ovsdb_idl_txn_add_comment(txn, ds_cstr(&comment));
2321     ds_destroy(&comment);
2322
2323     ovs = ovsrec_open_vswitch_first(idl);
2324     if (!ovs) {
2325         /* XXX add verification that table is empty */
2326         ovs = ovsrec_open_vswitch_insert(txn);
2327     }
2328
2329     if (wait_for_reload) {
2330         struct json *where = where_uuid_equals(&ovs->header_.uuid);
2331         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
2332         json_destroy(where);
2333     }
2334
2335     output = xmalloc(argc * sizeof *output);
2336     n_output = 0;
2337     for (start = i = 0; i <= argc; i++) {
2338         if (i == argc || !strcmp(argv[i], "--")) {
2339             if (i > start) {
2340                 ds_init(&output[n_output]);
2341                 run_vsctl_command(i - start, &argv[start], ovs, idl,
2342                                   &output[n_output++]);
2343             }
2344             start = i + 1;
2345         }
2346     }
2347
2348     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
2349         ovsdb_idl_run(idl);
2350         ovsdb_idl_wait(idl);
2351         ovsdb_idl_txn_wait(txn);
2352         poll_block();
2353     }
2354     if (wait_for_reload && status == TXN_SUCCESS) {
2355         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
2356     }
2357     ovsdb_idl_txn_destroy(txn);
2358
2359     switch (status) {
2360     case TXN_INCOMPLETE:
2361         NOT_REACHED();
2362
2363     case TXN_ABORTED:
2364         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2365         vsctl_fatal("transaction aborted");
2366
2367     case TXN_UNCHANGED:
2368     case TXN_SUCCESS:
2369         break;
2370
2371     case TXN_TRY_AGAIN:
2372         for (i = 0; i < n_output; i++) {
2373             ds_destroy(&output[i]);
2374         }
2375         return;
2376
2377     case TXN_ERROR:
2378         vsctl_fatal("transaction error");
2379
2380     default:
2381         NOT_REACHED();
2382     }
2383
2384     for (i = 0; i < n_output; i++) {
2385         struct ds *ds = &output[i];
2386         if (oneline) {
2387             size_t j;
2388
2389             ds_chomp(ds, '\n');
2390             for (j = 0; j < ds->length; j++) {
2391                 int c = ds->string[j];
2392                 switch (c) {
2393                 case '\n':
2394                     fputs("\\n", stdout);
2395                     break;
2396
2397                 case '\\':
2398                     fputs("\\\\", stdout);
2399                     break;
2400
2401                 default:
2402                     putchar(c);
2403                 }
2404             }
2405             putchar('\n');
2406         } else {
2407             fputs(ds_cstr(ds), stdout);
2408         }
2409     }
2410
2411     if (wait_for_reload && status != TXN_UNCHANGED) {
2412         for (;;) {
2413             const struct ovsrec_open_vswitch *ovs;
2414
2415             ovsdb_idl_run(idl);
2416             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
2417                 if (ovs->cur_cfg >= next_cfg) {
2418                     goto done;
2419                 }
2420             }
2421             ovsdb_idl_wait(idl);
2422             poll_block();
2423         }
2424     done: ;
2425     }
2426
2427     exit(EXIT_SUCCESS);
2428 }
2429
2430 static vsctl_handler_func *
2431 get_vsctl_handler(int argc, char *argv[], struct vsctl_context *ctx)
2432 {
2433     static const struct vsctl_command all_commands[] = {
2434         /* Open vSwitch commands. */
2435         {"init", 0, 0, cmd_init, ""},
2436
2437         /* Bridge commands. */
2438         {"add-br", 1, 3, cmd_add_br, ""},
2439         {"del-br", 1, 1, cmd_del_br, "--if-exists"},
2440         {"list-br", 0, 0, cmd_list_br, ""},
2441         {"br-exists", 1, 1, cmd_br_exists, ""},
2442         {"br-to-vlan", 1, 1, cmd_br_to_vlan, ""},
2443         {"br-to-parent", 1, 1, cmd_br_to_parent, ""},
2444         {"br-set-external-id", 2, 3, cmd_br_set_external_id, ""},
2445         {"br-get-external-id", 1, 2, cmd_br_get_external_id, ""},
2446
2447         /* Port commands. */
2448         {"list-ports", 1, 1, cmd_list_ports, ""},
2449         {"add-port", 2, 2, cmd_add_port, ""},
2450         {"add-bond", 4, INT_MAX, cmd_add_bond, "--fake-iface"},
2451         {"del-port", 1, 2, cmd_del_port, "--if-exists"},
2452         {"port-to-br", 1, 1, cmd_port_to_br, ""},
2453
2454         /* Interface commands. */
2455         {"list-ifaces", 1, 1, cmd_list_ifaces, ""},
2456         {"iface-to-br", 1, 1, cmd_iface_to_br, ""},
2457
2458         /* Controller commands. */
2459         {"get-controller", 0, 1, cmd_get_controller, ""},
2460         {"del-controller", 0, 1, cmd_del_controller, ""},
2461         {"set-controller", 1, 2, cmd_set_controller, ""},
2462         {"get-fail-mode", 0, 1, cmd_get_fail_mode, ""},
2463         {"del-fail-mode", 0, 1, cmd_del_fail_mode, ""},
2464         {"set-fail-mode", 1, 2, cmd_set_fail_mode, ""},
2465
2466         /* SSL commands. */
2467         {"get-ssl", 0, 0, cmd_get_ssl, ""},
2468         {"del-ssl", 0, 0, cmd_del_ssl, ""},
2469         {"set-ssl", 3, 3, cmd_set_ssl, "--bootstrap"},
2470
2471         /* Parameter commands. */
2472         {"get", 3, INT_MAX, cmd_get, ""},
2473         {"list", 1, INT_MAX, cmd_list, ""},
2474         {"set", 3, INT_MAX, cmd_set, "--force"},
2475         {"add", 4, INT_MAX, cmd_add, "--force"},
2476         {"remove", 4, INT_MAX, cmd_remove, "--force"},
2477         {"clear", 3, INT_MAX, cmd_clear, "--force"},
2478         {"create", 2, INT_MAX, cmd_create, "--force"},
2479         {"destroy", 1, INT_MAX, cmd_destroy, "--force,--if-exists"},
2480     };
2481
2482     const struct vsctl_command *p;
2483     int i;
2484
2485     shash_init(&ctx->options);
2486     for (i = 0; i < argc; i++) {
2487         if (argv[i][0] != '-') {
2488             break;
2489         }
2490         if (!shash_add_once(&ctx->options, argv[i], NULL)) {
2491             vsctl_fatal("'%s' option specified multiple times", argv[i]);
2492         }
2493     }
2494     if (i == argc) {
2495         vsctl_fatal("missing command name");
2496     }
2497
2498     for (p = all_commands; p < &all_commands[ARRAY_SIZE(all_commands)]; p++) {
2499         if (!strcmp(p->name, argv[i])) {
2500             struct shash_node *node;
2501             int n_arg;
2502
2503             SHASH_FOR_EACH (node, &ctx->options) {
2504                 const char *s = strstr(p->options, node->name);
2505                 int end = s ? s[strlen(node->name)] : EOF;
2506                 if (end != ',' && end != ' ' && end != '\0') {
2507                     vsctl_fatal("'%s' command has no '%s' option",
2508                                 argv[i], node->name);
2509                 }
2510             }
2511
2512             n_arg = argc - i - 1;
2513             if (n_arg < p->min_args) {
2514                 vsctl_fatal("'%s' command requires at least %d arguments",
2515                             p->name, p->min_args);
2516             } else if (n_arg > p->max_args) {
2517                 vsctl_fatal("'%s' command takes at most %d arguments",
2518                             p->name, p->max_args);
2519             } else {
2520                 ctx->argc = n_arg + 1;
2521                 ctx->argv = &argv[i];
2522                 return p->handler;
2523             }
2524         }
2525     }
2526
2527     vsctl_fatal("unknown command '%s'; use --help for help", argv[i]);
2528 }
2529
2530 static void
2531 check_vsctl_command(int argc, char *argv[])
2532 {
2533     struct vsctl_context ctx;
2534
2535     get_vsctl_handler(argc, argv, &ctx);
2536     shash_destroy(&ctx.options);
2537 }
2538
2539 static void
2540 run_vsctl_command(int argc, char *argv[],
2541                   const struct ovsrec_open_vswitch *ovs,
2542                   struct ovsdb_idl *idl, struct ds *output)
2543 {
2544     vsctl_handler_func *function;
2545     struct vsctl_context ctx;
2546
2547     function = get_vsctl_handler(argc, argv, &ctx);
2548     ctx.ovs = ovs;
2549     ctx.idl = idl;
2550     ds_init(&ctx.output);
2551     function(&ctx);
2552     *output = ctx.output;
2553     shash_destroy(&ctx.options);
2554 }