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