ovn-sbctl: Use environment var OVN_SB_DB to find the database by default.
[cascardo/ovs.git] / ovn / utilities / ovn-sbctl.c
1 /*
2  * Copyright (c) 2015 Nicira, Inc.
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 <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <getopt.h>
23 #include <inttypes.h>
24 #include <signal.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include "db-ctl-base.h"
31
32 #include "command-line.h"
33 #include "compiler.h"
34 #include "dynamic-string.h"
35 #include "fatal-signal.h"
36 #include "json.h"
37 #include "ovsdb-data.h"
38 #include "ovsdb-idl.h"
39 #include "poll-loop.h"
40 #include "process.h"
41 #include "sset.h"
42 #include "shash.h"
43 #include "stream-ssl.h"
44 #include "stream.h"
45 #include "table.h"
46 #include "timeval.h"
47 #include "util.h"
48 #include "openvswitch/vlog.h"
49 #include "ovn/lib/ovn-sb-idl.h"
50
51 VLOG_DEFINE_THIS_MODULE(sbctl);
52
53 struct sbctl_context;
54
55 /* --db: The database server to contact. */
56 static const char *db;
57
58 /* --oneline: Write each command's output as a single line? */
59 static bool oneline;
60
61 /* --dry-run: Do not commit any changes. */
62 static bool dry_run;
63
64 /* --timeout: Time to wait for a connection to 'db'. */
65 static int timeout;
66
67 /* Format for table output. */
68 static struct table_style table_style = TABLE_STYLE_DEFAULT;
69
70 /* The IDL we're using and the current transaction, if any.
71  * This is for use by sbctl_exit() only, to allow it to clean up.
72  * Other code should use its context arguments. */
73 static struct ovsdb_idl *the_idl;
74 static struct ovsdb_idl_txn *the_idl_txn;
75 OVS_NO_RETURN static void sbctl_exit(int status);
76
77 static void sbctl_cmd_init(void);
78 OVS_NO_RETURN static void usage(void);
79 static void parse_options(int argc, char *argv[], struct shash *local_options);
80 static const char *sbctl_default_db(void);
81 static void run_prerequisites(struct ctl_command[], size_t n_commands,
82                               struct ovsdb_idl *);
83 static void do_sbctl(const char *args, struct ctl_command *, size_t n,
84                      struct ovsdb_idl *);
85
86 int
87 main(int argc, char *argv[])
88 {
89     extern struct vlog_module VLM_reconnect;
90     struct ovsdb_idl *idl;
91     struct ctl_command *commands;
92     struct shash local_options;
93     unsigned int seqno;
94     size_t n_commands;
95     char *args;
96
97     set_program_name(argv[0]);
98     fatal_ignore_sigpipe();
99     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
100     vlog_set_levels(&VLM_reconnect, VLF_ANY_DESTINATION, VLL_WARN);
101     sbrec_init();
102
103     sbctl_cmd_init();
104
105     /* Log our arguments.  This is often valuable for debugging systems. */
106     args = process_escape_args(argv);
107     VLOG(ctl_might_write_to_db(argv) ? VLL_INFO : VLL_DBG, "Called as %s", args);
108
109     /* Parse command line. */
110     shash_init(&local_options);
111     parse_options(argc, argv, &local_options);
112     commands = ctl_parse_commands(argc - optind, argv + optind, &local_options,
113                                   &n_commands);
114
115     if (timeout) {
116         time_alarm(timeout);
117     }
118
119     /* Initialize IDL. */
120     idl = the_idl = ovsdb_idl_create(db, &sbrec_idl_class, false, false);
121     run_prerequisites(commands, n_commands, idl);
122
123     /* Execute the commands.
124      *
125      * 'seqno' is the database sequence number for which we last tried to
126      * execute our transaction.  There's no point in trying to commit more than
127      * once for any given sequence number, because if the transaction fails
128      * it's because the database changed and we need to obtain an up-to-date
129      * view of the database before we try the transaction again. */
130     seqno = ovsdb_idl_get_seqno(idl);
131     for (;;) {
132         ovsdb_idl_run(idl);
133         if (!ovsdb_idl_is_alive(idl)) {
134             int retval = ovsdb_idl_get_last_error(idl);
135             ctl_fatal("%s: database connection failed (%s)",
136                         db, ovs_retval_to_string(retval));
137         }
138
139         if (seqno != ovsdb_idl_get_seqno(idl)) {
140             seqno = ovsdb_idl_get_seqno(idl);
141             do_sbctl(args, commands, n_commands, idl);
142         }
143
144         if (seqno == ovsdb_idl_get_seqno(idl)) {
145             ovsdb_idl_wait(idl);
146             poll_block();
147         }
148     }
149 }
150
151 static const char *
152 sbctl_default_db(void)
153 {
154     static char *def;
155     if (!def) {
156         def = getenv("OVN_SB_DB");
157         if (!def) {
158             def = ctl_default_db();
159         }
160     }
161     return def;
162 }
163
164 static void
165 parse_options(int argc, char *argv[], struct shash *local_options)
166 {
167     enum {
168         OPT_DB = UCHAR_MAX + 1,
169         OPT_ONELINE,
170         OPT_NO_SYSLOG,
171         OPT_DRY_RUN,
172         OPT_PEER_CA_CERT,
173         OPT_LOCAL,
174         OPT_COMMANDS,
175         OPT_OPTIONS,
176         VLOG_OPTION_ENUMS,
177         TABLE_OPTION_ENUMS
178     };
179     static const struct option global_long_options[] = {
180         {"db", required_argument, NULL, OPT_DB},
181         {"no-syslog", no_argument, NULL, OPT_NO_SYSLOG},
182         {"dry-run", no_argument, NULL, OPT_DRY_RUN},
183         {"oneline", no_argument, NULL, OPT_ONELINE},
184         {"timeout", required_argument, NULL, 't'},
185         {"help", no_argument, NULL, 'h'},
186         {"commands", no_argument, NULL, OPT_COMMANDS},
187         {"options", no_argument, NULL, OPT_OPTIONS},
188         {"version", no_argument, NULL, 'V'},
189         VLOG_LONG_OPTIONS,
190         STREAM_SSL_LONG_OPTIONS,
191         TABLE_LONG_OPTIONS,
192         {NULL, 0, NULL, 0},
193     };
194     const int n_global_long_options = ARRAY_SIZE(global_long_options) - 1;
195     char *tmp, *short_options;
196
197     struct option *options;
198     size_t allocated_options;
199     size_t n_options;
200     size_t i;
201
202     tmp = ovs_cmdl_long_options_to_short_options(global_long_options);
203     short_options = xasprintf("+%s", tmp);
204     free(tmp);
205
206     /* We want to parse both global and command-specific options here, but
207      * getopt_long() isn't too convenient for the job.  We copy our global
208      * options into a dynamic array, then append all of the command-specific
209      * options. */
210     options = xmemdup(global_long_options, sizeof global_long_options);
211     allocated_options = ARRAY_SIZE(global_long_options);
212     n_options = n_global_long_options;
213     ctl_add_cmd_options(&options, &n_options, &allocated_options, OPT_LOCAL);
214     table_style.format = TF_LIST;
215
216     for (;;) {
217         int idx;
218         int c;
219
220         c = getopt_long(argc, argv, short_options, options, &idx);
221         if (c == -1) {
222             break;
223         }
224
225         switch (c) {
226         case OPT_DB:
227             db = optarg;
228             break;
229
230         case OPT_ONELINE:
231             oneline = true;
232             break;
233
234         case OPT_NO_SYSLOG:
235             vlog_set_levels(&VLM_sbctl, VLF_SYSLOG, VLL_WARN);
236             break;
237
238         case OPT_DRY_RUN:
239             dry_run = true;
240             break;
241
242         case OPT_LOCAL:
243             if (shash_find(local_options, options[idx].name)) {
244                 ctl_fatal("'%s' option specified multiple times",
245                             options[idx].name);
246             }
247             shash_add_nocopy(local_options,
248                              xasprintf("--%s", options[idx].name),
249                              optarg ? xstrdup(optarg) : NULL);
250             break;
251
252         case 'h':
253             usage();
254
255         case OPT_COMMANDS:
256             ctl_print_commands();
257
258         case OPT_OPTIONS:
259             ctl_print_options(global_long_options);
260
261         case 'V':
262             ovs_print_version(0, 0);
263             printf("DB Schema %s\n", sbrec_get_db_version());
264             exit(EXIT_SUCCESS);
265
266         case 't':
267             timeout = strtoul(optarg, NULL, 10);
268             if (timeout < 0) {
269                 ctl_fatal("value %s on -t or --timeout is invalid", optarg);
270             }
271             break;
272
273         VLOG_OPTION_HANDLERS
274         TABLE_OPTION_HANDLERS(&table_style)
275         STREAM_SSL_OPTION_HANDLERS
276
277         case '?':
278             exit(EXIT_FAILURE);
279
280         default:
281             abort();
282         }
283     }
284     free(short_options);
285
286     if (!db) {
287         db = sbctl_default_db();
288     }
289
290     for (i = n_global_long_options; options[i].name; i++) {
291         free(CONST_CAST(char *, options[i].name));
292     }
293     free(options);
294 }
295
296 static void
297 usage(void)
298 {
299     printf("\
300 %s: OVN southbound DB management utility\n\
301 \n\
302 For debugging and testing only, not for use in production.\n\
303 \n\
304 usage: %s [OPTIONS] COMMAND [ARG...]\n\
305 \n\
306 General commands:\n\
307   show                        print overview of database contents\n\
308 \n\
309 Chassis commands:\n\
310   chassis-add CHASSIS ENCAP-TYPE ENCAP-IP  create a new chassis named\n\
311                                            CHASSIS with one encapsulation\n\
312                                            entry of ENCAP-TYPE and ENCAP-IP\n\
313   chassis-del CHASSIS         delete CHASSIS and all of its encaps,\n\
314                               and gateway_ports\n\
315 \n\
316 Port binding commands:\n\
317   lport-bind LPORT CHASSIS    bind logical port LPORT to CHASSIS\n\
318   lport-unbind LPORT          reset the port binding of logical port LPORT\n\
319 \n\
320 Logical flow commands:\n\
321   lflow-list [DATAPATH]       List logical flows for all or a single datapath\n\
322   dump-flows [DATAPATH]       Alias for lflow-list\n\
323 \n\
324 %s\
325 \n\
326 Options:\n\
327   --db=DATABASE               connect to DATABASE\n\
328                               (default: %s)\n\
329   -t, --timeout=SECS          wait at most SECS seconds\n\
330   --dry-run                   do not commit changes to database\n\
331   --oneline                   print exactly one line of output per command\n",
332            program_name, program_name, ctl_get_db_cmd_usage(), ctl_default_db());
333     vlog_usage();
334     printf("\
335   --no-syslog             equivalent to --verbose=sbctl:syslog:warn\n");
336     printf("\n\
337 Other options:\n\
338   -h, --help                  display this help message\n\
339   -V, --version               display version information\n");
340     stream_usage("database", true, true, false);
341     exit(EXIT_SUCCESS);
342 }
343
344 \f
345 /* ovs-sbctl specific context.  Inherits the 'struct ctl_context' as base. */
346 struct sbctl_context {
347     struct ctl_context base;
348
349     /* A cache of the contents of the database.
350      *
351      * A command that needs to use any of this information must first call
352      * sbctl_context_populate_cache().  A command that changes anything that
353      * could invalidate the cache must either call
354      * sbctl_context_invalidate_cache() or manually update the cache to
355      * maintain its correctness. */
356     bool cache_valid;
357     /* Maps from chassis name to struct sbctl_chassis. */
358     struct shash chassis;
359     /* Maps from lport name to struct sbctl_port_binding. */
360     struct shash port_bindings;
361 };
362
363 /* Casts 'base' into 'struct sbctl_context'. */
364 static struct sbctl_context *
365 sbctl_context_cast(struct ctl_context *base)
366 {
367     return CONTAINER_OF(base, struct sbctl_context, base);
368 }
369
370 struct sbctl_chassis {
371     const struct sbrec_chassis *ch_cfg;
372 };
373
374 struct sbctl_port_binding {
375     const struct sbrec_port_binding *bd_cfg;
376 };
377
378 static void
379 sbctl_context_invalidate_cache(struct ctl_context *ctx)
380 {
381     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
382
383     if (!sbctl_ctx->cache_valid) {
384         return;
385     }
386     sbctl_ctx->cache_valid = false;
387     shash_destroy_free_data(&sbctl_ctx->chassis);
388     shash_destroy_free_data(&sbctl_ctx->port_bindings);
389 }
390
391 static void
392 sbctl_context_populate_cache(struct ctl_context *ctx)
393 {
394     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
395     const struct sbrec_chassis *chassis_rec;
396     const struct sbrec_port_binding *port_binding_rec;
397     struct sset chassis, port_bindings;
398
399     if (sbctl_ctx->cache_valid) {
400         /* Cache is already populated. */
401         return;
402     }
403     sbctl_ctx->cache_valid = true;
404     shash_init(&sbctl_ctx->chassis);
405     shash_init(&sbctl_ctx->port_bindings);
406     sset_init(&chassis);
407     SBREC_CHASSIS_FOR_EACH(chassis_rec, ctx->idl) {
408         struct sbctl_chassis *ch;
409
410         if (!sset_add(&chassis, chassis_rec->name)) {
411             VLOG_WARN("database contains duplicate chassis name (%s)",
412                       chassis_rec->name);
413             continue;
414         }
415
416         ch = xmalloc(sizeof *ch);
417         ch->ch_cfg = chassis_rec;
418         shash_add(&sbctl_ctx->chassis, chassis_rec->name, ch);
419     }
420     sset_destroy(&chassis);
421
422     sset_init(&port_bindings);
423     SBREC_PORT_BINDING_FOR_EACH(port_binding_rec, ctx->idl) {
424         struct sbctl_port_binding *bd;
425
426         if (!sset_add(&port_bindings, port_binding_rec->logical_port)) {
427             VLOG_WARN("database contains duplicate port binding for logical "
428                       "port (%s)",
429                       port_binding_rec->logical_port);
430             continue;
431         }
432
433         bd = xmalloc(sizeof *bd);
434         bd->bd_cfg = port_binding_rec;
435         shash_add(&sbctl_ctx->port_bindings, port_binding_rec->logical_port,
436                   bd);
437     }
438     sset_destroy(&port_bindings);
439 }
440
441 static void
442 check_conflicts(struct sbctl_context *sbctl_ctx, const char *name,
443                 char *msg)
444 {
445     if (shash_find(&sbctl_ctx->chassis, name)) {
446         ctl_fatal("%s because a chassis named %s already exists",
447                     msg, name);
448     }
449     free(msg);
450 }
451
452 static struct sbctl_chassis *
453 find_chassis(struct sbctl_context *sbctl_ctx, const char *name,
454              bool must_exist)
455 {
456     struct sbctl_chassis *sbctl_ch;
457
458     ovs_assert(sbctl_ctx->cache_valid);
459
460     sbctl_ch = shash_find_data(&sbctl_ctx->chassis, name);
461     if (must_exist && !sbctl_ch) {
462         ctl_fatal("no chassis named %s", name);
463     }
464
465     return sbctl_ch;
466 }
467
468 static struct sbctl_port_binding *
469 find_port_binding(struct sbctl_context *sbctl_ctx, const char *name,
470                   bool must_exist)
471 {
472     struct sbctl_port_binding *bd;
473
474     ovs_assert(sbctl_ctx->cache_valid);
475
476     bd = shash_find_data(&sbctl_ctx->port_bindings, name);
477     if (must_exist && !bd) {
478         ctl_fatal("no port named %s", name);
479     }
480
481     return bd;
482 }
483
484 static void
485 pre_get_info(struct ctl_context *ctx)
486 {
487     ovsdb_idl_add_column(ctx->idl, &sbrec_chassis_col_name);
488     ovsdb_idl_add_column(ctx->idl, &sbrec_chassis_col_encaps);
489
490     ovsdb_idl_add_column(ctx->idl, &sbrec_encap_col_type);
491     ovsdb_idl_add_column(ctx->idl, &sbrec_encap_col_ip);
492
493     ovsdb_idl_add_column(ctx->idl, &sbrec_port_binding_col_logical_port);
494     ovsdb_idl_add_column(ctx->idl, &sbrec_port_binding_col_chassis);
495
496     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_logical_datapath);
497     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_pipeline);
498     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_actions);
499     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_priority);
500     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_table_id);
501     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_match);
502     ovsdb_idl_add_column(ctx->idl, &sbrec_logical_flow_col_external_ids);
503 }
504
505 static struct cmd_show_table cmd_show_tables[] = {
506     {&sbrec_table_chassis,
507      &sbrec_chassis_col_name,
508      {&sbrec_chassis_col_encaps,
509       NULL,
510       NULL},
511      {&sbrec_table_port_binding,
512       &sbrec_port_binding_col_logical_port,
513       &sbrec_port_binding_col_chassis}},
514
515     {&sbrec_table_encap,
516      &sbrec_encap_col_type,
517      {&sbrec_encap_col_ip,
518       &sbrec_encap_col_options,
519       NULL},
520      {NULL, NULL, NULL}},
521
522     {NULL, NULL, {NULL, NULL, NULL}, {NULL, NULL, NULL}},
523 };
524
525 static void
526 cmd_chassis_add(struct ctl_context *ctx)
527 {
528     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
529     struct sbrec_chassis *ch;
530     struct sbrec_encap *encap;
531     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
532     const char *ch_name, *encap_type, *encap_ip;
533
534     ch_name = ctx->argv[1];
535     encap_type = ctx->argv[2];
536     encap_ip = ctx->argv[3];
537
538     sbctl_context_populate_cache(ctx);
539     if (may_exist) {
540         struct sbctl_chassis *sbctl_ch;
541
542         sbctl_ch = find_chassis(sbctl_ctx, ch_name, false);
543         if (sbctl_ch) {
544             return;
545         }
546     }
547     check_conflicts(sbctl_ctx, ch_name,
548                     xasprintf("cannot create a chassis named %s", ch_name));
549     ch = sbrec_chassis_insert(ctx->txn);
550     sbrec_chassis_set_name(ch, ch_name);
551     encap = sbrec_encap_insert(ctx->txn);
552     sbrec_encap_set_type(encap, encap_type);
553     sbrec_encap_set_ip(encap, encap_ip);
554     sbrec_chassis_set_encaps(ch, &encap, 1);
555     sbctl_context_invalidate_cache(ctx);
556 }
557
558 static void
559 cmd_chassis_del(struct ctl_context *ctx)
560 {
561     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
562     bool must_exist = !shash_find(&ctx->options, "--if-exists");
563     struct sbctl_chassis *sbctl_ch;
564
565     sbctl_context_populate_cache(ctx);
566     sbctl_ch = find_chassis(sbctl_ctx, ctx->argv[1], must_exist);
567     if (sbctl_ch) {
568         if (sbctl_ch->ch_cfg) {
569             size_t i;
570
571             for (i = 0; i < sbctl_ch->ch_cfg->n_encaps; i++) {
572                 sbrec_encap_delete(sbctl_ch->ch_cfg->encaps[i]);
573             }
574             sbrec_chassis_delete(sbctl_ch->ch_cfg);
575         }
576         shash_find_and_delete(&sbctl_ctx->chassis, ctx->argv[1]);
577         free(sbctl_ch);
578     }
579 }
580
581 static void
582 cmd_lport_bind(struct ctl_context *ctx)
583 {
584     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
585     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
586     struct sbctl_chassis *sbctl_ch;
587     struct sbctl_port_binding *sbctl_bd;
588     char *lport_name, *ch_name;
589
590     /* port_binding must exist, chassis must exist! */
591     lport_name = ctx->argv[1];
592     ch_name = ctx->argv[2];
593
594     sbctl_context_populate_cache(ctx);
595     sbctl_bd = find_port_binding(sbctl_ctx, lport_name, true);
596     sbctl_ch = find_chassis(sbctl_ctx, ch_name, true);
597
598     if (sbctl_bd->bd_cfg->chassis) {
599         if (may_exist && sbctl_bd->bd_cfg->chassis == sbctl_ch->ch_cfg) {
600             return;
601         } else {
602             ctl_fatal("lport (%s) has already been binded to chassis (%s)",
603                       lport_name, sbctl_bd->bd_cfg->chassis->name);
604         }
605     }
606     sbrec_port_binding_set_chassis(sbctl_bd->bd_cfg, sbctl_ch->ch_cfg);
607     sbctl_context_invalidate_cache(ctx);
608 }
609
610 static void
611 cmd_lport_unbind(struct ctl_context *ctx)
612 {
613     struct sbctl_context *sbctl_ctx = sbctl_context_cast(ctx);
614     bool must_exist = !shash_find(&ctx->options, "--if-exists");
615     struct sbctl_port_binding *sbctl_bd;
616     char *lport_name;
617
618     lport_name = ctx->argv[1];
619     sbctl_context_populate_cache(ctx);
620     sbctl_bd = find_port_binding(sbctl_ctx, lport_name, must_exist);
621     if (sbctl_bd) {
622         sbrec_port_binding_set_chassis(sbctl_bd->bd_cfg, NULL);
623     }
624 }
625
626 enum {
627     PL_INGRESS,
628     PL_EGRESS,
629 };
630
631 /* Help ensure we catch any future pipeline values */
632 static int
633 pipeline_encode(const char *pl)
634 {
635     if (!strcmp(pl, "ingress")) {
636         return PL_INGRESS;
637     } else if (!strcmp(pl, "egress")) {
638         return PL_EGRESS;
639     }
640
641     OVS_NOT_REACHED();
642 }
643
644 static int
645 lflow_cmp(const void *lf1_, const void *lf2_)
646 {
647     const struct sbrec_logical_flow *const *lf1p = lf1_;
648     const struct sbrec_logical_flow *const *lf2p = lf2_;
649     const struct sbrec_logical_flow *lf1 = *lf1p;
650     const struct sbrec_logical_flow *lf2 = *lf2p;
651
652     int pl1 = pipeline_encode(lf1->pipeline);
653     int pl2 = pipeline_encode(lf2->pipeline);
654
655 #define CMP(expr) \
656     do { \
657         int res; \
658         res = (expr); \
659         if (res) { \
660             return res; \
661         } \
662     } while (0)
663
664     CMP(uuid_compare_3way(&lf1->logical_datapath->header_.uuid,
665                           &lf2->logical_datapath->header_.uuid));
666     CMP(pl1 - pl2);
667     CMP(lf1->table_id > lf2->table_id ? 1 :
668             (lf1->table_id < lf2->table_id ? -1 : 0));
669     CMP(lf1->priority > lf2->priority ? -1 :
670             (lf1->priority < lf2->priority ? 1 : 0));
671     CMP(strcmp(lf1->match, lf2->match));
672
673 #undef CMP
674
675     return 0;
676 }
677
678 static void
679 cmd_lflow_list(struct ctl_context *ctx)
680 {
681     const char *datapath = ctx->argc == 2 ? ctx->argv[1] : NULL;
682     struct uuid datapath_uuid = { .parts = { 0, }};
683     const struct sbrec_logical_flow **lflows;
684     const struct sbrec_logical_flow *lflow;
685     size_t n_flows = 0, n_capacity = 64;
686
687     if (datapath && !uuid_from_string(&datapath_uuid, datapath)) {
688         VLOG_ERR("Invalid format of datapath UUID");
689         return;
690     }
691
692     lflows = xmalloc(sizeof *lflows * n_capacity);
693     SBREC_LOGICAL_FLOW_FOR_EACH (lflow, ctx->idl) {
694         if (n_flows == n_capacity) {
695             lflows = x2nrealloc(lflows, &n_capacity, sizeof *lflows);
696         }
697         lflows[n_flows] = lflow;
698         n_flows++;
699     }
700
701     qsort(lflows, n_flows, sizeof *lflows, lflow_cmp);
702
703     const char *cur_pipeline = "";
704     size_t i;
705     for (i = 0; i < n_flows; i++) {
706         lflow = lflows[i];
707         if (datapath && !uuid_equals(&datapath_uuid,
708                                      &lflow->logical_datapath->header_.uuid)) {
709             continue;
710         }
711         if (strcmp(cur_pipeline, lflow->pipeline)) {
712             printf("Datapath: " UUID_FMT "  Pipeline: %s\n",
713                     UUID_ARGS(&lflow->logical_datapath->header_.uuid),
714                     lflow->pipeline);
715             cur_pipeline = lflow->pipeline;
716         }
717
718         const char *table_name = smap_get(&lflow->external_ids, "stage-name");
719         printf("  table=%" PRId64 "(%8s), priority=%5" PRId64
720                ", match=(%s), action=(%s)\n",
721                lflow->table_id, table_name ? table_name : "",
722                lflow->priority, lflow->match, lflow->actions);
723     }
724
725     free(lflows);
726 }
727
728 \f
729 static const struct ctl_table_class tables[] = {
730     {&sbrec_table_chassis,
731      {{&sbrec_table_chassis, &sbrec_chassis_col_name, NULL},
732       {NULL, NULL, NULL}}},
733
734     {&sbrec_table_encap,
735      {{NULL, NULL, NULL},
736       {NULL, NULL, NULL}}},
737
738     {&sbrec_table_logical_flow,
739      {{&sbrec_table_logical_flow, NULL,
740        &sbrec_logical_flow_col_logical_datapath},
741       {NULL, NULL, NULL}}},
742
743     {&sbrec_table_multicast_group,
744      {{NULL, NULL, NULL},
745       {NULL, NULL, NULL}}},
746
747     {&sbrec_table_datapath_binding,
748      {{NULL, NULL, NULL},
749       {NULL, NULL, NULL}}},
750
751     {&sbrec_table_port_binding,
752      {{&sbrec_table_port_binding, &sbrec_port_binding_col_logical_port, NULL},
753       {NULL, NULL, NULL}}},
754
755     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
756 };
757
758 \f
759 static void
760 sbctl_context_init_command(struct sbctl_context *sbctl_ctx,
761                            struct ctl_command *command)
762 {
763     ctl_context_init_command(&sbctl_ctx->base, command);
764 }
765
766 static void
767 sbctl_context_init(struct sbctl_context *sbctl_ctx,
768                    struct ctl_command *command, struct ovsdb_idl *idl,
769                    struct ovsdb_idl_txn *txn,
770                    struct ovsdb_symbol_table *symtab)
771 {
772     ctl_context_init(&sbctl_ctx->base, command, idl, txn, symtab,
773                      sbctl_context_invalidate_cache);
774     sbctl_ctx->cache_valid = false;
775 }
776
777 static void
778 sbctl_context_done_command(struct sbctl_context *sbctl_ctx,
779                            struct ctl_command *command)
780 {
781     ctl_context_done_command(&sbctl_ctx->base, command);
782 }
783
784 static void
785 sbctl_context_done(struct sbctl_context *sbctl_ctx,
786                    struct ctl_command *command)
787 {
788     ctl_context_done(&sbctl_ctx->base, command);
789 }
790
791 static void
792 run_prerequisites(struct ctl_command *commands, size_t n_commands,
793                   struct ovsdb_idl *idl)
794 {
795     struct ctl_command *c;
796
797     for (c = commands; c < &commands[n_commands]; c++) {
798         if (c->syntax->prerequisites) {
799             struct sbctl_context sbctl_ctx;
800
801             ds_init(&c->output);
802             c->table = NULL;
803
804             sbctl_context_init(&sbctl_ctx, c, idl, NULL, NULL);
805             (c->syntax->prerequisites)(&sbctl_ctx.base);
806             sbctl_context_done(&sbctl_ctx, c);
807
808             ovs_assert(!c->output.string);
809             ovs_assert(!c->table);
810         }
811     }
812 }
813
814 static void
815 do_sbctl(const char *args, struct ctl_command *commands, size_t n_commands,
816          struct ovsdb_idl *idl)
817 {
818     struct ovsdb_idl_txn *txn;
819     enum ovsdb_idl_txn_status status;
820     struct ovsdb_symbol_table *symtab;
821     struct sbctl_context sbctl_ctx;
822     struct ctl_command *c;
823     struct shash_node *node;
824     char *error = NULL;
825
826     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
827     if (dry_run) {
828         ovsdb_idl_txn_set_dry_run(txn);
829     }
830
831     ovsdb_idl_txn_add_comment(txn, "ovs-sbctl: %s", args);
832
833     symtab = ovsdb_symbol_table_create();
834     for (c = commands; c < &commands[n_commands]; c++) {
835         ds_init(&c->output);
836         c->table = NULL;
837     }
838     sbctl_context_init(&sbctl_ctx, NULL, idl, txn, symtab);
839     for (c = commands; c < &commands[n_commands]; c++) {
840         sbctl_context_init_command(&sbctl_ctx, c);
841         if (c->syntax->run) {
842             (c->syntax->run)(&sbctl_ctx.base);
843         }
844         sbctl_context_done_command(&sbctl_ctx, c);
845
846         if (sbctl_ctx.base.try_again) {
847             sbctl_context_done(&sbctl_ctx, NULL);
848             goto try_again;
849         }
850     }
851     sbctl_context_done(&sbctl_ctx, NULL);
852
853     SHASH_FOR_EACH (node, &symtab->sh) {
854         struct ovsdb_symbol *symbol = node->data;
855         if (!symbol->created) {
856             ctl_fatal("row id \"%s\" is referenced but never created (e.g. "
857                       "with \"-- --id=%s create ...\")",
858                       node->name, node->name);
859         }
860         if (!symbol->strong_ref) {
861             if (!symbol->weak_ref) {
862                 VLOG_WARN("row id \"%s\" was created but no reference to it "
863                           "was inserted, so it will not actually appear in "
864                           "the database", node->name);
865             } else {
866                 VLOG_WARN("row id \"%s\" was created but only a weak "
867                           "reference to it was inserted, so it will not "
868                           "actually appear in the database", node->name);
869             }
870         }
871     }
872
873     status = ovsdb_idl_txn_commit_block(txn);
874     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
875         for (c = commands; c < &commands[n_commands]; c++) {
876             if (c->syntax->postprocess) {
877                 sbctl_context_init(&sbctl_ctx, c, idl, txn, symtab);
878                 (c->syntax->postprocess)(&sbctl_ctx.base);
879                 sbctl_context_done(&sbctl_ctx, c);
880             }
881         }
882     }
883     error = xstrdup(ovsdb_idl_txn_get_error(txn));
884
885     switch (status) {
886     case TXN_UNCOMMITTED:
887     case TXN_INCOMPLETE:
888         OVS_NOT_REACHED();
889
890     case TXN_ABORTED:
891         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
892         ctl_fatal("transaction aborted");
893
894     case TXN_UNCHANGED:
895     case TXN_SUCCESS:
896         break;
897
898     case TXN_TRY_AGAIN:
899         goto try_again;
900
901     case TXN_ERROR:
902         ctl_fatal("transaction error: %s", error);
903
904     case TXN_NOT_LOCKED:
905         /* Should not happen--we never call ovsdb_idl_set_lock(). */
906         ctl_fatal("database not locked");
907
908     default:
909         OVS_NOT_REACHED();
910     }
911     free(error);
912
913     ovsdb_symbol_table_destroy(symtab);
914
915     for (c = commands; c < &commands[n_commands]; c++) {
916         struct ds *ds = &c->output;
917
918         if (c->table) {
919             table_print(c->table, &table_style);
920         } else if (oneline) {
921             size_t j;
922
923             ds_chomp(ds, '\n');
924             for (j = 0; j < ds->length; j++) {
925                 int ch = ds->string[j];
926                 switch (ch) {
927                 case '\n':
928                     fputs("\\n", stdout);
929                     break;
930
931                 case '\\':
932                     fputs("\\\\", stdout);
933                     break;
934
935                 default:
936                     putchar(ch);
937                 }
938             }
939             putchar('\n');
940         } else {
941             fputs(ds_cstr(ds), stdout);
942         }
943         ds_destroy(&c->output);
944         table_destroy(c->table);
945         free(c->table);
946
947         shash_destroy_free_data(&c->options);
948     }
949     free(commands);
950     ovsdb_idl_txn_destroy(txn);
951     ovsdb_idl_destroy(idl);
952
953     exit(EXIT_SUCCESS);
954
955 try_again:
956     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
957      * resources and return so that the caller can try again. */
958     if (txn) {
959         ovsdb_idl_txn_abort(txn);
960         ovsdb_idl_txn_destroy(txn);
961         the_idl_txn = NULL;
962     }
963     ovsdb_symbol_table_destroy(symtab);
964     for (c = commands; c < &commands[n_commands]; c++) {
965         ds_destroy(&c->output);
966         table_destroy(c->table);
967         free(c->table);
968     }
969     free(error);
970 }
971
972 /* Frees the current transaction and the underlying IDL and then calls
973  * exit(status).
974  *
975  * Freeing the transaction and the IDL is not strictly necessary, but it makes
976  * for a clean memory leak report from valgrind in the normal case.  That makes
977  * it easier to notice real memory leaks. */
978 static void
979 sbctl_exit(int status)
980 {
981     if (the_idl_txn) {
982         ovsdb_idl_txn_abort(the_idl_txn);
983         ovsdb_idl_txn_destroy(the_idl_txn);
984     }
985     ovsdb_idl_destroy(the_idl);
986     exit(status);
987 }
988
989 static const struct ctl_command_syntax sbctl_commands[] = {
990     /* Chassis commands. */
991     {"chassis-add", 3, 3, "CHASSIS ENCAP-TYPE ENCAP-IP", pre_get_info,
992      cmd_chassis_add, NULL, "--may-exist", RW},
993     {"chassis-del", 1, 1, "CHASSIS", pre_get_info, cmd_chassis_del, NULL,
994      "--if-exists", RW},
995
996     /* Port binding commands. */
997     {"lport-bind", 2, 2, "LPORT CHASSIS", pre_get_info, cmd_lport_bind, NULL,
998      "--may-exist", RW},
999     {"lport-unbind", 1, 1, "LPORT", pre_get_info, cmd_lport_unbind, NULL,
1000      "--if-exists", RW},
1001
1002     /* Logical flow commands */
1003     {"lflow-list", 0, 1, "[DATAPATH]", pre_get_info, cmd_lflow_list, NULL,
1004      "", RO},
1005     {"dump-flows", 0, 1, "[DATAPATH]", pre_get_info, cmd_lflow_list, NULL,
1006      "", RO}, /* Friendly alias for lflow-list */
1007
1008     /* SSL commands (To Be Added). */
1009
1010     {NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, RO},
1011 };
1012
1013 /* Registers sbctl and common db commands. */
1014 static void
1015 sbctl_cmd_init(void)
1016 {
1017     ctl_init(tables, cmd_show_tables, sbctl_exit);
1018     ctl_register_commands(sbctl_commands);
1019 }