ofproto: Remove support for OpenFlow-based management protocol.
[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_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_downdelay, 0, "[0,]"},
1571     {&ovsrec_port_col_bond_fake_iface, VSCF_READONLY, NULL},
1572     {&ovsrec_port_col_bond_updelay, 0, "[0,]"},
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         if (best_score && !referrer) {
1749             ovs_fatal(0, "multiple rows in %s match \"%s\"",
1750                       table->class->name, record_id);
1751         }
1752     }
1753     if (!referrer) {
1754         return NULL;
1755     }
1756
1757     final = NULL;
1758     if (id->uuid_column) {
1759         struct ovsdb_datum uuid;
1760
1761         assert(id->uuid_column->type.key_type == OVSDB_TYPE_UUID);
1762         assert(id->uuid_column->type.value_type == OVSDB_TYPE_VOID);
1763
1764         ovsdb_idl_txn_read(referrer, id->uuid_column, &uuid);
1765         if (uuid.n == 1) {
1766             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
1767                                                &uuid.keys[0].uuid);
1768         }
1769         ovsdb_datum_destroy(&uuid, &id->uuid_column->type);
1770     } else {
1771         final = referrer;
1772     }
1773
1774     return final;
1775 }
1776
1777 static const struct ovsdb_idl_row *
1778 get_row(struct vsctl_context *ctx,
1779         const struct vsctl_table_class *table, const char *record_id)
1780 {
1781     const struct ovsdb_idl_row *row;
1782     struct uuid uuid;
1783
1784     if (uuid_from_string(&uuid, record_id)) {
1785         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
1786     } else {
1787         int i;
1788
1789         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
1790             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
1791             if (row) {
1792                 break;
1793             }
1794         }
1795     }
1796     return row;
1797 }
1798
1799 static const struct ovsdb_idl_row *
1800 must_get_row(struct vsctl_context *ctx,
1801              const struct vsctl_table_class *table, const char *record_id)
1802 {
1803     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
1804     if (!row) {
1805         ovs_fatal(0, "no row \"%s\" in table %s",
1806                   record_id, table->class->name);
1807     }
1808     return row;
1809 }
1810
1811 static char *
1812 get_column(const struct vsctl_table_class *table, const char *column_name,
1813            const struct vsctl_column **columnp)
1814 {
1815     const struct vsctl_column *column;
1816     const struct vsctl_column *best_match = NULL;
1817     unsigned int best_score = 0;
1818
1819     for (column = table->columns; column->idl; column++) {
1820         if (!(column->flags & VSCF_HIDDEN)) {
1821             unsigned int score = score_partial_match(column->idl->name,
1822                                                      column_name);
1823             if (score > best_score) {
1824                 best_match = column;
1825                 best_score = score;
1826             } else if (score == best_score) {
1827                 best_match = NULL;
1828             }
1829         }
1830     }
1831
1832     *columnp = best_match;
1833     if (best_match) {
1834         return NULL;
1835     } else if (best_score) {
1836         return xasprintf("%s contains more than one column whose name "
1837                          "matches \"%s\"", table->class->name, column_name);
1838     } else {
1839         return xasprintf("%s does not contain a column whose name matches "
1840                          "\"%s\"", table->class->name, column_name);
1841     }
1842 }
1843
1844 static char * WARN_UNUSED_RESULT
1845 parse_column_key_value(const char *arg, const struct vsctl_table_class *table,
1846                        const struct vsctl_column **columnp,
1847                        char **keyp, char **valuep)
1848 {
1849     const char *p = arg;
1850     char *error;
1851
1852     assert(columnp || keyp);
1853     if (keyp) {
1854         *keyp = NULL;
1855     }
1856     if (valuep) {
1857         *valuep = NULL;
1858     }
1859
1860     /* Parse column name. */
1861     if (columnp) {
1862         char *column_name;
1863
1864         error = ovsdb_token_parse(&p, &column_name);
1865         if (error) {
1866             goto error;
1867         }
1868         if (column_name[0] == '\0') {
1869             free(column_name);
1870             error = xasprintf("%s: missing column name", arg);
1871             goto error;
1872         }
1873         error = get_column(table, column_name, columnp);
1874         if (error) {
1875             goto error;
1876         }
1877         free(column_name);
1878     }
1879
1880     /* Parse key string. */
1881     if (*p == ':' || !columnp) {
1882         if (columnp) {
1883             p++;
1884         } else if (!keyp) {
1885             error = xasprintf("%s: key not accepted here", arg);
1886             goto error;
1887         }
1888         error = ovsdb_token_parse(&p, keyp);
1889         if (error) {
1890             goto error;
1891         }
1892     } else if (keyp) {
1893         *keyp = NULL;
1894     }
1895
1896     /* Parse value string. */
1897     if (*p == '=') {
1898         if (!valuep) {
1899             error = xasprintf("%s: value not accepted here", arg);
1900             goto error;
1901         }
1902         *valuep = xstrdup(p + 1);
1903     } else {
1904         if (valuep) {
1905             *valuep = NULL;
1906         }
1907         if (*p != '\0') {
1908             error = xasprintf("%s: trailing garbage \"%s\" in argument",
1909                               arg, p);
1910             goto error;
1911         }
1912     }
1913     return NULL;
1914
1915 error:
1916     if (columnp) {
1917         *columnp = NULL;
1918     }
1919     if (keyp) {
1920         free(*keyp);
1921         *keyp = NULL;
1922     }
1923     if (valuep) {
1924         free(*valuep);
1925         *valuep = NULL;
1926     }
1927     return error;
1928 }
1929
1930 static void
1931 cmd_get(struct vsctl_context *ctx)
1932 {
1933     bool if_exists = shash_find(&ctx->options, "--if-exists");
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                 if (!if_exists) {
1969                     ovs_fatal(0, "no key \"%s\" in %s record \"%s\" column %s",
1970                               key_string, table->class->name, record_id,
1971                               column->idl->name);
1972                 }
1973             } else {
1974                 ovsdb_atom_to_string(&datum.values[idx],
1975                                      column->idl->type.value_type, out);
1976             }
1977             ovsdb_atom_destroy(&key, column->idl->type.key_type);
1978         } else {
1979             ovsdb_datum_to_string(&datum, &column->idl->type, out);
1980         }
1981         ds_put_char(out, '\n');
1982         ovsdb_datum_destroy(&datum, &column->idl->type);
1983
1984         free(key_string);
1985     }
1986 }
1987
1988 static void
1989 list_record(const struct vsctl_table_class *table,
1990             const struct ovsdb_idl_row *row, struct ds *out)
1991 {
1992     const struct vsctl_column *column;
1993
1994     ds_put_format(out, "%-20s (RO): "UUID_FMT"\n", "_uuid",
1995                   UUID_ARGS(&row->uuid));
1996     for (column = table->columns; column->idl; column++) {
1997         struct ovsdb_datum datum;
1998
1999         if (column->flags & VSCF_HIDDEN) {
2000             continue;
2001         }
2002
2003         ovsdb_idl_txn_read(row, column->idl, &datum);
2004
2005         ds_put_format(out, "%-20s (%s): ", column->idl->name,
2006                       column->flags & VSCF_READONLY ? "RO" : "RW");
2007         ovsdb_datum_to_string(&datum, &column->idl->type, out);
2008         ds_put_char(out, '\n');
2009
2010         ovsdb_datum_destroy(&datum, &column->idl->type);
2011     }
2012 }
2013
2014 static void
2015 cmd_list(struct vsctl_context *ctx)
2016 {
2017     const char *table_name = ctx->argv[1];
2018     const struct vsctl_table_class *table;
2019     struct ds *out = &ctx->output;
2020     int i;
2021
2022     table = get_table(table_name);
2023     if (ctx->argc > 2) {
2024         for (i = 2; i < ctx->argc; i++) {
2025             if (i > 2) {
2026                 ds_put_char(out, '\n');
2027             }
2028             list_record(table, must_get_row(ctx, table, ctx->argv[i]), out);
2029         }
2030     } else {
2031         const struct ovsdb_idl_row *row;
2032         bool first;
2033
2034         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
2035              row != NULL;
2036              row = ovsdb_idl_next_row(row), first = false) {
2037             if (!first) {
2038                 ds_put_char(out, '\n');
2039             }
2040             list_record(table, row, out);
2041         }
2042     }
2043 }
2044
2045 static void
2046 check_string_constraint(const struct ovsdb_datum *datum,
2047                         const char *constraint)
2048 {
2049     unsigned int i;
2050     char *regex;
2051     regex_t re;
2052     int retval;
2053
2054     regex = xasprintf("^%s$", constraint);
2055     retval = regcomp(&re, regex, REG_NOSUB | REG_EXTENDED);
2056     if (retval) {
2057         size_t length = regerror(retval, &re, NULL, 0);
2058         char *buffer = xmalloc(length);
2059         regerror(retval, &re, buffer, length);
2060         ovs_fatal(0, "internal error compiling regular expression %s: %s",
2061                   regex, buffer);
2062     }
2063
2064     for (i = 0; i < datum->n; i++) {
2065         const char *key = datum->keys[i].string;
2066         if (regexec(&re, key, 0, NULL, 0)) {
2067             ovs_fatal(0, "%s is not valid (it does not match %s)", key, regex);
2068         }
2069     }
2070     free(regex);
2071     regfree(&re);
2072 }
2073
2074 static void
2075 check_integer_constraint(const struct ovsdb_datum *datum,
2076                          const char *constraint)
2077 {
2078     int64_t min, max;
2079     unsigned int i;
2080     int n = -1;
2081
2082     sscanf(constraint, "[%"SCNd64",%"SCNd64"]%n", &min, &max, &n);
2083     if (n == -1) {
2084         sscanf(constraint, "[%"SCNd64",]%n", &min, &n);
2085         if (n == -1) {
2086             sscanf(constraint, "[,%"SCNd64"]%n", &max, &n);
2087             if (n == -1) {
2088                 VLOG_DBG("internal error: bad integer contraint \"%s\"",
2089                          constraint);
2090                 return;
2091             } else {
2092                 min = INT64_MIN;
2093             }
2094         } else {
2095             max = INT64_MAX;
2096         }
2097     }
2098
2099     for (i = 0; i < datum->n; i++) {
2100         int64_t value = datum->keys[i].integer;
2101         if (value < min || value > max) {
2102             if (max == INT64_MAX) {
2103                 ovs_fatal(0, "%"PRId64" is less than the minimum "
2104                           "allowed value %"PRId64, value, min);
2105             } else if (min == INT64_MIN) {
2106                 ovs_fatal(0, "%"PRId64" is greater than the maximum "
2107                           "allowed value %"PRId64, value, max);
2108             } else {
2109                 ovs_fatal(0, "%"PRId64" is outside the valid range %"PRId64" "
2110                           "to %"PRId64" (inclusive)", value, min, max);
2111             }
2112         }
2113     }
2114 }
2115
2116 static void
2117 check_constraint(const struct ovsdb_datum *datum,
2118                  const struct ovsdb_type *type, const char *constraint)
2119 {
2120     if (constraint && datum->n) {
2121         if (type->key_type == OVSDB_TYPE_STRING) {
2122             check_string_constraint(datum, constraint);
2123         } else if (type->key_type == OVSDB_TYPE_INTEGER) {
2124             check_integer_constraint(datum, constraint);
2125         }
2126     }
2127 }
2128
2129 static void
2130 set_column(const struct vsctl_table_class *table,
2131            const struct ovsdb_idl_row *row,
2132            const char *arg, bool force)
2133 {
2134     const struct vsctl_column *column;
2135     char *key_string, *value_string;
2136     char *error;
2137
2138     error = parse_column_key_value(arg, table, &column, &key_string,
2139                                    &value_string);
2140     die_if_error(error);
2141     if (column->flags & VSCF_READONLY && !force) {
2142         ovs_fatal(0, "%s: cannot modify read-only column %s in table %s",
2143                   arg, column->idl->name, table->class->name);
2144     }
2145     if (!value_string) {
2146         ovs_fatal(0, "%s: missing value", arg);
2147     }
2148
2149     if (key_string) {
2150         union ovsdb_atom key, value;
2151         struct ovsdb_datum old, new;
2152
2153         if (column->idl->type.value_type == OVSDB_TYPE_VOID) {
2154             ovs_fatal(0, "cannot specify key to set for non-map column %s",
2155                       column->idl->name);
2156         }
2157
2158         die_if_error(ovsdb_atom_from_string(&key,
2159                                             column->idl->type.key_type,
2160                                             key_string));
2161         die_if_error(ovsdb_atom_from_string(&value,
2162                                             column->idl->type.value_type,
2163                                             value_string));
2164
2165         ovsdb_datum_init_empty(&new);
2166         ovsdb_datum_add_unsafe(&new, &key, &value, &column->idl->type);
2167
2168         ovsdb_idl_txn_read(row, column->idl, &old);
2169         ovsdb_datum_union(&old, &new, &column->idl->type, true);
2170         ovsdb_idl_txn_write(row, column->idl, &old);
2171
2172         ovsdb_datum_destroy(&new, &column->idl->type);
2173     } else {
2174         struct ovsdb_datum datum;
2175
2176         die_if_error(ovsdb_datum_from_string(&datum, &column->idl->type,
2177                                              value_string));
2178         if (!force) {
2179             check_constraint(&datum, &column->idl->type,
2180                              column->constraint);
2181         }
2182         ovsdb_idl_txn_write(row, column->idl, &datum);
2183     }
2184
2185     free(key_string);
2186 }
2187
2188 static void
2189 cmd_set(struct vsctl_context *ctx)
2190 {
2191     bool force = shash_find(&ctx->options, "--force");
2192     const char *table_name = ctx->argv[1];
2193     const char *record_id = ctx->argv[2];
2194     const struct vsctl_table_class *table;
2195     const struct ovsdb_idl_row *row;
2196     int i;
2197
2198     table = get_table(table_name);
2199     row = must_get_row(ctx, table, record_id);
2200     for (i = 3; i < ctx->argc; i++) {
2201         set_column(table, row, ctx->argv[i], force);
2202     }
2203 }
2204
2205 static void
2206 cmd_add(struct vsctl_context *ctx)
2207 {
2208     bool force = shash_find(&ctx->options, "--force");
2209     const char *table_name = ctx->argv[1];
2210     const char *record_id = ctx->argv[2];
2211     const char *column_name = ctx->argv[3];
2212     const struct vsctl_table_class *table;
2213     const struct vsctl_column *column;
2214     const struct ovsdb_idl_row *row;
2215     const struct ovsdb_type *type;
2216     struct ovsdb_datum old;
2217     int i;
2218
2219     table = get_table(table_name);
2220     row = must_get_row(ctx, table, record_id);
2221     die_if_error(get_column(table, column_name, &column));
2222     if (column->flags & VSCF_READONLY && !force) {
2223         ovs_fatal(0, "cannot modify read-only column %s in table %s",
2224                    column->idl->name, table->class->name);
2225     }
2226
2227     type = &column->idl->type;
2228     ovsdb_idl_txn_read(row, column->idl, &old);
2229     for (i = 4; i < ctx->argc; i++) {
2230         struct ovsdb_type add_type;
2231         struct ovsdb_datum add;
2232
2233         add_type = *type;
2234         add_type.n_min = 1;
2235         add_type.n_max = UINT_MAX;
2236         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i]));
2237         ovsdb_datum_union(&old, &add, type, false);
2238         ovsdb_datum_destroy(&add, type);
2239     }
2240     if (old.n > type->n_max) {
2241         ovs_fatal(0, "\"add\" operation would put %u %s in column %s of "
2242                   "table %s but the maximum number is %u",
2243                   old.n,
2244                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2245                   column->idl->name, table->class->name, type->n_max);
2246     }
2247     ovsdb_idl_txn_write(row, column->idl, &old);
2248 }
2249
2250 static void
2251 cmd_remove(struct vsctl_context *ctx)
2252 {
2253     bool force = shash_find(&ctx->options, "--force");
2254     const char *table_name = ctx->argv[1];
2255     const char *record_id = ctx->argv[2];
2256     const char *column_name = ctx->argv[3];
2257     const struct vsctl_table_class *table;
2258     const struct vsctl_column *column;
2259     const struct ovsdb_idl_row *row;
2260     const struct ovsdb_type *type;
2261     struct ovsdb_datum old;
2262     int i;
2263
2264     table = get_table(table_name);
2265     row = must_get_row(ctx, table, record_id);
2266     die_if_error(get_column(table, column_name, &column));
2267     if (column->flags & VSCF_READONLY && !force) {
2268         ovs_fatal(0, "cannot modify read-only column %s in table %s",
2269                    column->idl->name, table->class->name);
2270     }
2271
2272     type = &column->idl->type;
2273     ovsdb_idl_txn_read(row, column->idl, &old);
2274     for (i = 4; i < ctx->argc; i++) {
2275         struct ovsdb_type rm_type;
2276         struct ovsdb_datum rm;
2277         char *error;
2278
2279         rm_type = *type;
2280         rm_type.n_min = 1;
2281         rm_type.n_max = UINT_MAX;
2282         error = ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]);
2283         if (error && ovsdb_type_is_map(&rm_type)) {
2284             free(error);
2285             rm_type.value_type = OVSDB_TYPE_VOID;
2286             die_if_error(ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]));
2287         }
2288         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
2289         ovsdb_datum_destroy(&rm, &rm_type);
2290     }
2291     if (old.n < type->n_min) {
2292         ovs_fatal(0, "\"remove\" operation would put %u %s in column %s of "
2293                   "table %s but the minimun number is %u",
2294                   old.n,
2295                   type->value_type == OVSDB_TYPE_VOID ? "values" : "pairs",
2296                   column->idl->name, table->class->name, type->n_min);
2297     }
2298     ovsdb_idl_txn_write(row, column->idl, &old);
2299 }
2300
2301 static void
2302 cmd_clear(struct vsctl_context *ctx)
2303 {
2304     bool force = shash_find(&ctx->options, "--force");
2305     const char *table_name = ctx->argv[1];
2306     const char *record_id = ctx->argv[2];
2307     const struct vsctl_table_class *table;
2308     const struct ovsdb_idl_row *row;
2309     int i;
2310
2311     table = get_table(table_name);
2312     row = must_get_row(ctx, table, record_id);
2313     for (i = 3; i < ctx->argc; i++) {
2314         const struct vsctl_column *column;
2315         const struct ovsdb_type *type;
2316         struct ovsdb_datum datum;
2317
2318         die_if_error(get_column(table, ctx->argv[i], &column));
2319
2320         type = &column->idl->type;
2321         if (column->flags & VSCF_READONLY && !force) {
2322             ovs_fatal(0, "cannot modify read-only column %s in table %s",
2323                       column->idl->name, table->class->name);
2324         } else if (type->n_min > 0) {
2325             ovs_fatal(0, "\"clear\" operation cannot be applied to column %s "
2326                       "of table %s, which is not allowed to be empty",
2327                       column->idl->name, table->class->name);
2328         }
2329
2330         ovsdb_datum_init_empty(&datum);
2331         ovsdb_idl_txn_write(row, column->idl, &datum);
2332     }
2333 }
2334
2335 static void
2336 cmd_create(struct vsctl_context *ctx)
2337 {
2338     bool force = shash_find(&ctx->options, "--force");
2339     const char *table_name = ctx->argv[1];
2340     const struct vsctl_table_class *table;
2341     const struct ovsdb_idl_row *row;
2342     int i;
2343
2344     if (!force) {
2345         ovs_fatal(0, "\"create\" requires --force");
2346     }
2347
2348     table = get_table(table_name);
2349     row = ovsdb_idl_txn_insert(ctx->txn, table->class);
2350     for (i = 2; i < ctx->argc; i++) {
2351         set_column(table, row, ctx->argv[i], force);
2352     }
2353     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
2354 }
2355
2356 /* This function may be used as the 'postprocess' function for commands that
2357  * insert new rows into the database.  It expects that the command's 'run'
2358  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
2359  * sole output.  It replaces that output by the row's permanent UUID assigned
2360  * by the database server and appends a new-line.
2361  *
2362  * Currently we use this only for "create", because the higher-level commands
2363  * are supposed to be independent of the actual structure of the vswitch
2364  * configuration. */
2365 static void
2366 post_create(struct vsctl_context *ctx)
2367 {
2368     const struct uuid *real;
2369     struct uuid dummy;
2370
2371     uuid_from_string(&dummy, ds_cstr(&ctx->output));
2372     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
2373     if (real) {
2374         ds_clear(&ctx->output);
2375         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
2376     }
2377     ds_put_char(&ctx->output, '\n');
2378 }
2379
2380 static void
2381 cmd_destroy(struct vsctl_context *ctx)
2382 {
2383     bool force = shash_find(&ctx->options, "--force");
2384     bool must_exist = !shash_find(&ctx->options, "--if-exists");
2385     const char *table_name = ctx->argv[1];
2386     const struct vsctl_table_class *table;
2387     int i;
2388
2389     if (!force) {
2390         ovs_fatal(0, "\"destroy\" requires --force");
2391     }
2392
2393     table = get_table(table_name);
2394     for (i = 2; i < ctx->argc; i++) {
2395         const struct ovsdb_idl_row *row;
2396
2397         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
2398         if (row) {
2399             ovsdb_idl_txn_delete(row);
2400         }
2401     }
2402 }
2403 \f
2404 static struct json *
2405 where_uuid_equals(const struct uuid *uuid)
2406 {
2407     return
2408         json_array_create_1(
2409             json_array_create_3(
2410                 json_string_create("_uuid"),
2411                 json_string_create("=="),
2412                 json_array_create_2(
2413                     json_string_create("uuid"),
2414                     json_string_create_nocopy(
2415                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
2416 }
2417
2418 static void
2419 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
2420                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
2421                    const struct ovsrec_open_vswitch *ovs)
2422 {
2423     ctx->argc = command->argc;
2424     ctx->argv = command->argv;
2425     ctx->options = command->options;
2426
2427     ds_swap(&ctx->output, &command->output);
2428     ctx->idl = idl;
2429     ctx->txn = txn;
2430     ctx->ovs = ovs;
2431
2432 }
2433
2434 static void
2435 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
2436 {
2437     ds_swap(&ctx->output, &command->output);
2438 }
2439
2440 static void
2441 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
2442          struct ovsdb_idl *idl)
2443 {
2444     struct ovsdb_idl_txn *txn;
2445     const struct ovsrec_open_vswitch *ovs;
2446     enum ovsdb_idl_txn_status status;
2447     struct vsctl_command *c;
2448     int64_t next_cfg = 0;
2449     char *comment;
2450
2451     txn = ovsdb_idl_txn_create(idl);
2452     if (dry_run) {
2453         ovsdb_idl_txn_set_dry_run(txn);
2454     }
2455
2456     comment = xasprintf("ovs-vsctl: %s", args);
2457     ovsdb_idl_txn_add_comment(txn, comment);
2458     free(comment);
2459
2460     ovs = ovsrec_open_vswitch_first(idl);
2461     if (!ovs) {
2462         /* XXX add verification that table is empty */
2463         ovs = ovsrec_open_vswitch_insert(txn);
2464     }
2465
2466     if (wait_for_reload) {
2467         struct json *where = where_uuid_equals(&ovs->header_.uuid);
2468         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
2469         json_destroy(where);
2470     }
2471
2472     for (c = commands; c < &commands[n_commands]; c++) {
2473         struct vsctl_context ctx;
2474
2475         ds_init(&c->output);
2476         vsctl_context_init(&ctx, c, idl, txn, ovs);
2477         (c->syntax->run)(&ctx);
2478         vsctl_context_done(&ctx, c);
2479     }
2480
2481     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
2482         ovsdb_idl_run(idl);
2483         ovsdb_idl_wait(idl);
2484         ovsdb_idl_txn_wait(txn);
2485         poll_block();
2486     }
2487     if (wait_for_reload && status == TXN_SUCCESS) {
2488         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
2489     }
2490     for (c = commands; c < &commands[n_commands]; c++) {
2491         if (c->syntax->postprocess) {
2492             struct vsctl_context ctx;
2493
2494             vsctl_context_init(&ctx, c, idl, txn, ovs);
2495             (c->syntax->postprocess)(&ctx);
2496             vsctl_context_done(&ctx, c);
2497         }
2498     }
2499     ovsdb_idl_txn_destroy(txn);
2500
2501     switch (status) {
2502     case TXN_INCOMPLETE:
2503         NOT_REACHED();
2504
2505     case TXN_ABORTED:
2506         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2507         vsctl_fatal("transaction aborted");
2508
2509     case TXN_UNCHANGED:
2510     case TXN_SUCCESS:
2511         break;
2512
2513     case TXN_TRY_AGAIN:
2514         for (c = commands; c < &commands[n_commands]; c++) {
2515             ds_destroy(&c->output);
2516         }
2517         return;
2518
2519     case TXN_ERROR:
2520         vsctl_fatal("transaction error");
2521
2522     default:
2523         NOT_REACHED();
2524     }
2525
2526     for (c = commands; c < &commands[n_commands]; c++) {
2527         struct ds *ds = &c->output;
2528         if (oneline) {
2529             size_t j;
2530
2531             ds_chomp(ds, '\n');
2532             for (j = 0; j < ds->length; j++) {
2533                 int c = ds->string[j];
2534                 switch (c) {
2535                 case '\n':
2536                     fputs("\\n", stdout);
2537                     break;
2538
2539                 case '\\':
2540                     fputs("\\\\", stdout);
2541                     break;
2542
2543                 default:
2544                     putchar(c);
2545                 }
2546             }
2547             putchar('\n');
2548         } else {
2549             fputs(ds_cstr(ds), stdout);
2550         }
2551     }
2552
2553     if (wait_for_reload && status != TXN_UNCHANGED) {
2554         for (;;) {
2555             const struct ovsrec_open_vswitch *ovs;
2556
2557             ovsdb_idl_run(idl);
2558             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
2559                 if (ovs->cur_cfg >= next_cfg) {
2560                     goto done;
2561                 }
2562             }
2563             ovsdb_idl_wait(idl);
2564             poll_block();
2565         }
2566     done: ;
2567     }
2568
2569     exit(EXIT_SUCCESS);
2570 }
2571
2572 static const struct vsctl_command_syntax all_commands[] = {
2573     /* Open vSwitch commands. */
2574     {"init", 0, 0, cmd_init, NULL, ""},
2575
2576     /* Bridge commands. */
2577     {"add-br", 1, 3, cmd_add_br, NULL, ""},
2578     {"del-br", 1, 1, cmd_del_br, NULL, "--if-exists"},
2579     {"list-br", 0, 0, cmd_list_br, NULL, ""},
2580     {"br-exists", 1, 1, cmd_br_exists, NULL, ""},
2581     {"br-to-vlan", 1, 1, cmd_br_to_vlan, NULL, ""},
2582     {"br-to-parent", 1, 1, cmd_br_to_parent, NULL, ""},
2583     {"br-set-external-id", 2, 3, cmd_br_set_external_id, NULL, ""},
2584     {"br-get-external-id", 1, 2, cmd_br_get_external_id, NULL, ""},
2585
2586     /* Port commands. */
2587     {"list-ports", 1, 1, cmd_list_ports, NULL, ""},
2588     {"add-port", 2, 2, cmd_add_port, NULL, ""},
2589     {"add-bond", 4, INT_MAX, cmd_add_bond, NULL, "--fake-iface"},
2590     {"del-port", 1, 2, cmd_del_port, NULL, "--if-exists"},
2591     {"port-to-br", 1, 1, cmd_port_to_br, NULL, ""},
2592
2593     /* Interface commands. */
2594     {"list-ifaces", 1, 1, cmd_list_ifaces, NULL, ""},
2595     {"iface-to-br", 1, 1, cmd_iface_to_br, NULL, ""},
2596
2597     /* Controller commands. */
2598     {"get-controller", 0, 1, cmd_get_controller, NULL, ""},
2599     {"del-controller", 0, 1, cmd_del_controller, NULL, ""},
2600     {"set-controller", 1, 2, cmd_set_controller, NULL, ""},
2601     {"get-fail-mode", 0, 1, cmd_get_fail_mode, NULL, ""},
2602     {"del-fail-mode", 0, 1, cmd_del_fail_mode, NULL, ""},
2603     {"set-fail-mode", 1, 2, cmd_set_fail_mode, NULL, ""},
2604
2605     /* SSL commands. */
2606     {"get-ssl", 0, 0, cmd_get_ssl, NULL, ""},
2607     {"del-ssl", 0, 0, cmd_del_ssl, NULL, ""},
2608     {"set-ssl", 3, 3, cmd_set_ssl, NULL, "--bootstrap"},
2609
2610     /* Parameter commands. */
2611     {"get", 3, INT_MAX, cmd_get, NULL, "--if-exists"},
2612     {"list", 1, INT_MAX, cmd_list, NULL, ""},
2613     {"set", 3, INT_MAX, cmd_set, NULL, "--force"},
2614     {"add", 4, INT_MAX, cmd_add, NULL, "--force"},
2615     {"remove", 4, INT_MAX, cmd_remove, NULL, "--force"},
2616     {"clear", 3, INT_MAX, cmd_clear, NULL, "--force"},
2617     {"create", 2, INT_MAX, cmd_create, post_create, "--force"},
2618     {"destroy", 1, INT_MAX, cmd_destroy, NULL, "--force,--if-exists"},
2619
2620     {NULL, 0, 0, NULL, NULL, NULL},
2621 };
2622