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