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