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