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