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