ovn-nbctl: add db commands help and manpage
[cascardo/ovs.git] / ovn / utilities / ovn-nbctl.c
1 /*
2  * Licensed under the Apache License, Version 2.0 (the "License");
3  * you may not use this file except in compliance with the License.
4  * You may obtain a copy of the License at:
5  *
6  *     http://www.apache.org/licenses/LICENSE-2.0
7  *
8  * Unless required by applicable law or agreed to in writing, software
9  * distributed under the License is distributed on an "AS IS" BASIS,
10  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  * See the License for the specific language governing permissions and
12  * limitations under the License.
13  */
14
15 #include <config.h>
16
17 #include <getopt.h>
18 #include <inttypes.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21
22 #include "command-line.h"
23 #include "db-ctl-base.h"
24 #include "dirs.h"
25 #include "fatal-signal.h"
26 #include "json.h"
27 #include "ovn/lib/ovn-nb-idl.h"
28 #include "poll-loop.h"
29 #include "process.h"
30 #include "smap.h"
31 #include "stream.h"
32 #include "stream-ssl.h"
33 #include "svec.h"
34 #include "table.h"
35 #include "timeval.h"
36 #include "util.h"
37 #include "openvswitch/vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(nbctl);
40
41 /* --db: The database server to contact. */
42 static const char *db;
43
44 /* --oneline: Write each command's output as a single line? */
45 static bool oneline;
46
47 /* --dry-run: Do not commit any changes. */
48 static bool dry_run;
49
50 /* --timeout: Time to wait for a connection to 'db'. */
51 static int timeout;
52
53 /* Format for table output. */
54 static struct table_style table_style = TABLE_STYLE_DEFAULT;
55
56 /* The IDL we're using and the current transaction, if any.
57  * This is for use by nbctl_exit() only, to allow it to clean up.
58  * Other code should use its context arguments. */
59 static struct ovsdb_idl *the_idl;
60 static struct ovsdb_idl_txn *the_idl_txn;
61 OVS_NO_RETURN static void nbctl_exit(int status);
62
63 static void nbctl_cmd_init(void);
64 OVS_NO_RETURN static void usage(void);
65 static void parse_options(int argc, char *argv[], struct shash *local_options);
66 static const char *nbctl_default_db(void);
67 static void run_prerequisites(struct ctl_command[], size_t n_commands,
68                               struct ovsdb_idl *);
69 static void do_nbctl(const char *args, struct ctl_command *, size_t n,
70                      struct ovsdb_idl *);
71
72 int
73 main(int argc, char *argv[])
74 {
75     extern struct vlog_module VLM_reconnect;
76     struct ovsdb_idl *idl;
77     struct ctl_command *commands;
78     struct shash local_options;
79     unsigned int seqno;
80     size_t n_commands;
81     char *args;
82
83     set_program_name(argv[0]);
84     fatal_ignore_sigpipe();
85     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
86     vlog_set_levels(&VLM_reconnect, VLF_ANY_DESTINATION, VLL_WARN);
87     nbrec_init();
88
89     nbctl_cmd_init();
90
91     /* Log our arguments.  This is often valuable for debugging systems. */
92     args = process_escape_args(argv);
93     VLOG(ctl_might_write_to_db(argv) ? VLL_INFO : VLL_DBG,
94          "Called as %s", args);
95
96     /* Parse command line. */
97     shash_init(&local_options);
98     parse_options(argc, argv, &local_options);
99     commands = ctl_parse_commands(argc - optind, argv + optind, &local_options,
100                                   &n_commands);
101
102     if (timeout) {
103         time_alarm(timeout);
104     }
105
106     /* Initialize IDL. */
107     idl = the_idl = ovsdb_idl_create(db, &nbrec_idl_class, true, false);
108     run_prerequisites(commands, n_commands, idl);
109
110     /* Execute the commands.
111      *
112      * 'seqno' is the database sequence number for which we last tried to
113      * execute our transaction.  There's no point in trying to commit more than
114      * once for any given sequence number, because if the transaction fails
115      * it's because the database changed and we need to obtain an up-to-date
116      * view of the database before we try the transaction again. */
117     seqno = ovsdb_idl_get_seqno(idl);
118     for (;;) {
119         ovsdb_idl_run(idl);
120         if (!ovsdb_idl_is_alive(idl)) {
121             int retval = ovsdb_idl_get_last_error(idl);
122             ctl_fatal("%s: database connection failed (%s)",
123                         db, ovs_retval_to_string(retval));
124         }
125
126         if (seqno != ovsdb_idl_get_seqno(idl)) {
127             seqno = ovsdb_idl_get_seqno(idl);
128             do_nbctl(args, commands, n_commands, idl);
129         }
130
131         if (seqno == ovsdb_idl_get_seqno(idl)) {
132             ovsdb_idl_wait(idl);
133             poll_block();
134         }
135     }
136 }
137
138 static const char *
139 nbctl_default_db(void)
140 {
141     static char *def;
142     if (!def) {
143         def = getenv("OVN_NB_DB");
144         if (!def) {
145             def = ctl_default_db();
146         }
147     }
148     return def;
149 }
150
151 static void
152 parse_options(int argc, char *argv[], struct shash *local_options)
153 {
154     enum {
155         OPT_DB = UCHAR_MAX + 1,
156         OPT_NO_SYSLOG,
157         OPT_DRY_RUN,
158         OPT_ONELINE,
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_nbctl, 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             exit(EXIT_SUCCESS);
241
242         case OPT_COMMANDS:
243             ctl_print_commands();
244
245         case OPT_OPTIONS:
246             ctl_print_options(global_long_options);
247
248         case 'V':
249             ovs_print_version(0, 0);
250             printf("DB Schema %s\n", nbrec_get_db_version());
251             exit(EXIT_SUCCESS);
252
253         case 't':
254             timeout = strtoul(optarg, NULL, 10);
255             if (timeout < 0) {
256                 ctl_fatal("value %s on -t or --timeout is invalid", optarg);
257             }
258             break;
259
260         VLOG_OPTION_HANDLERS
261         TABLE_OPTION_HANDLERS(&table_style)
262         STREAM_SSL_OPTION_HANDLERS
263
264         case '?':
265             exit(EXIT_FAILURE);
266
267         default:
268             abort();
269         }
270     }
271     free(short_options);
272
273     if (!db) {
274         db = nbctl_default_db();
275     }
276
277     for (i = n_global_long_options; options[i].name; i++) {
278         free(CONST_CAST(char *, options[i].name));
279     }
280     free(options);
281 }
282
283 static void
284 usage(void)
285 {
286     printf("\
287 %s: OVN northbound DB management utility\n\
288 usage: %s [OPTIONS] COMMAND [ARG...]\n\
289 \n\
290 General commands:\n\
291   show                      print overview of database contents\n\
292   show LSWITCH              print overview of database contents for LSWITCH\n\
293 \n\
294 Logical switch commands:\n\
295   lswitch-add [LSWITCH]     create a logical switch named LSWITCH\n\
296   lswitch-del LSWITCH       delete LSWITCH and all its ports\n\
297   lswitch-list              print the names of all logical switches\n\
298 \n\
299 ACL commands:\n\
300   acl-add LSWITCH DIRECTION PRIORITY MATCH ACTION [log]\n\
301                             add an ACL to LSWITCH\n\
302   acl-del LSWITCH [DIRECTION [PRIORITY MATCH]]\n\
303                             remove ACLs from LSWITCH\n\
304   acl-list LSWITCH          print ACLs for LSWITCH\n\
305 \n\
306 Logical port commands:\n\
307   lport-add LSWITCH LPORT   add logical port LPORT on LSWITCH\n\
308   lport-add LSWITCH LPORT PARENT TAG\n\
309                             add logical port LPORT on LSWITCH with PARENT\n\
310                             on TAG\n\
311   lport-del LPORT           delete LPORT from its attached switch\n\
312   lport-list LSWITCH        print the names of all logical ports on LSWITCH\n\
313   lport-get-parent LPORT    get the parent of LPORT if set\n\
314   lport-get-tag LPORT       get the LPORT's tag if set\n\
315   lport-set-addresses LPORT [ADDRESS]...\n\
316                             set MAC or MAC+IP addresses for LPORT.\n\
317   lport-get-addresses LPORT      get a list of MAC addresses on LPORT\n\
318   lport-set-port-security LPORT [ADDRS]...\n\
319                             set port security addresses for LPORT.\n\
320   lport-get-port-security LPORT    get LPORT's port security addresses\n\
321   lport-get-up LPORT        get state of LPORT ('up' or 'down')\n\
322   lport-set-enabled LPORT STATE\n\
323                             set administrative state LPORT\n\
324                             ('enabled' or 'disabled')\n\
325   lport-get-enabled LPORT   get administrative state LPORT\n\
326                             ('enabled' or 'disabled')\n\
327   lport-set-type LPORT TYPE Set the type for LPORT\n\
328   lport-get-type LPORT      Get the type for LPORT\n\
329   lport-set-options LPORT KEY=VALUE [KEY=VALUE]...\n\
330                             Set options related to the type of LPORT\n\
331   lport-get-options LPORT   Get the type specific options for LPORT\n\
332 \n\
333 %s\
334 \n\
335 Options:\n\
336   --db=DATABASE               connect to DATABASE\n\
337                               (default: %s)\n\
338   -t, --timeout=SECS          wait at most SECS seconds\n\
339   --dry-run                   do not commit changes to database\n\
340   --oneline                   print exactly one line of output per command\n",
341            program_name, program_name, ctl_get_db_cmd_usage(), nbctl_default_db());
342     vlog_usage();
343     printf("\
344   --no-syslog             equivalent to --verbose=nbctl:syslog:warn\n");
345     printf("\n\
346 Other options:\n\
347   -h, --help                  display this help message\n\
348   -V, --version               display version information\n");
349     exit(EXIT_SUCCESS);
350 }
351 \f
352 static const struct nbrec_logical_switch *
353 lswitch_by_name_or_uuid(struct ctl_context *ctx, const char *id)
354 {
355     const struct nbrec_logical_switch *lswitch = NULL;
356     bool is_uuid = false;
357     bool duplicate = false;
358     struct uuid lswitch_uuid;
359
360     if (uuid_from_string(&lswitch_uuid, id)) {
361         is_uuid = true;
362         lswitch = nbrec_logical_switch_get_for_uuid(ctx->idl,
363                                                     &lswitch_uuid);
364     }
365
366     if (!lswitch) {
367         const struct nbrec_logical_switch *iter;
368
369         NBREC_LOGICAL_SWITCH_FOR_EACH(iter, ctx->idl) {
370             if (strcmp(iter->name, id)) {
371                 continue;
372             }
373             if (lswitch) {
374                 VLOG_WARN("There is more than one logical switch named '%s'. "
375                         "Use a UUID.", id);
376                 lswitch = NULL;
377                 duplicate = true;
378                 break;
379             }
380             lswitch = iter;
381         }
382     }
383
384     if (!lswitch && !duplicate) {
385         VLOG_WARN("lswitch not found for %s: '%s'",
386                 is_uuid ? "UUID" : "name", id);
387     }
388
389     return lswitch;
390 }
391
392 static void
393 print_lswitch(const struct nbrec_logical_switch *lswitch, struct ds *s)
394 {
395     ds_put_format(s, "    lswitch "UUID_FMT" (%s)\n",
396                   UUID_ARGS(&lswitch->header_.uuid), lswitch->name);
397
398     for (size_t i = 0; i < lswitch->n_ports; i++) {
399         const struct nbrec_logical_port *lport = lswitch->ports[i];
400
401         ds_put_format(s, "        lport %s\n", lport->name);
402         if (lport->parent_name) {
403             ds_put_format(s, "            parent: %s\n", lport->parent_name);
404         }
405         if (lport->n_tag) {
406             ds_put_format(s, "            tag: %"PRIu64"\n", lport->tag[0]);
407         }
408         if (lport->n_addresses) {
409             ds_put_cstr(s, "            addresses:");
410             for (size_t j = 0; j < lport->n_addresses; j++) {
411                 ds_put_format(s, " %s", lport->addresses[j]);
412             }
413             ds_put_char(s, '\n');
414         }
415     }
416 }
417
418 static void
419 nbctl_show(struct ctl_context *ctx)
420 {
421     const struct nbrec_logical_switch *lswitch;
422
423     if (ctx->argc == 2) {
424         lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
425         if (lswitch) {
426             print_lswitch(lswitch, &ctx->output);
427         }
428     } else {
429         NBREC_LOGICAL_SWITCH_FOR_EACH(lswitch, ctx->idl) {
430             print_lswitch(lswitch, &ctx->output);
431         }
432     }
433 }
434
435 static void
436 nbctl_lswitch_add(struct ctl_context *ctx)
437 {
438     struct nbrec_logical_switch *lswitch;
439
440     lswitch = nbrec_logical_switch_insert(ctx->txn);
441     if (ctx->argc == 2) {
442         nbrec_logical_switch_set_name(lswitch, ctx->argv[1]);
443     }
444 }
445
446 static void
447 nbctl_lswitch_del(struct ctl_context *ctx)
448 {
449     const char *id = ctx->argv[1];
450     const struct nbrec_logical_switch *lswitch;
451
452     lswitch = lswitch_by_name_or_uuid(ctx, id);
453     if (!lswitch) {
454         return;
455     }
456
457     nbrec_logical_switch_delete(lswitch);
458 }
459
460 static void
461 nbctl_lswitch_list(struct ctl_context *ctx)
462 {
463     const struct nbrec_logical_switch *lswitch;
464     struct smap lswitches;
465
466     smap_init(&lswitches);
467     NBREC_LOGICAL_SWITCH_FOR_EACH(lswitch, ctx->idl) {
468         smap_add_format(&lswitches, lswitch->name, UUID_FMT " (%s)",
469                         UUID_ARGS(&lswitch->header_.uuid), lswitch->name);
470     }
471     const struct smap_node **nodes = smap_sort(&lswitches);
472     for (size_t i = 0; i < smap_count(&lswitches); i++) {
473         const struct smap_node *node = nodes[i];
474         ds_put_format(&ctx->output, "%s\n", node->value);
475     }
476     smap_destroy(&lswitches);
477     free(nodes);
478 }
479 \f
480 static const struct nbrec_logical_port *
481 lport_by_name_or_uuid(struct ctl_context *ctx, const char *id)
482 {
483     const struct nbrec_logical_port *lport = NULL;
484     bool is_uuid = false;
485     struct uuid lport_uuid;
486
487     if (uuid_from_string(&lport_uuid, id)) {
488         is_uuid = true;
489         lport = nbrec_logical_port_get_for_uuid(ctx->idl, &lport_uuid);
490     }
491
492     if (!lport) {
493         NBREC_LOGICAL_PORT_FOR_EACH(lport, ctx->idl) {
494             if (!strcmp(lport->name, id)) {
495                 break;
496             }
497         }
498     }
499
500     if (!lport) {
501         VLOG_WARN("lport not found for %s: '%s'",
502                 is_uuid ? "UUID" : "name", id);
503     }
504
505     return lport;
506 }
507
508 static void
509 nbctl_lport_add(struct ctl_context *ctx)
510 {
511     struct nbrec_logical_port *lport;
512     const struct nbrec_logical_switch *lswitch;
513     int64_t tag;
514
515     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
516     if (!lswitch) {
517         return;
518     }
519
520     if (ctx->argc != 3 && ctx->argc != 5) {
521         /* If a parent_name is specified, a tag must be specified as well. */
522         VLOG_WARN("Invalid arguments to lport-add.");
523         return;
524     }
525
526     if (ctx->argc == 5) {
527         /* Validate tag. */
528         if (!ovs_scan(ctx->argv[4], "%"SCNd64, &tag) || tag < 0 || tag > 4095) {
529             VLOG_WARN("Invalid tag '%s'", ctx->argv[4]);
530             return;
531         }
532     }
533
534     /* Create the logical port. */
535     lport = nbrec_logical_port_insert(ctx->txn);
536     nbrec_logical_port_set_name(lport, ctx->argv[2]);
537     if (ctx->argc == 5) {
538         nbrec_logical_port_set_parent_name(lport, ctx->argv[3]);
539         nbrec_logical_port_set_tag(lport, &tag, 1);
540     }
541
542     /* Insert the logical port into the logical switch. */
543     nbrec_logical_switch_verify_ports(lswitch);
544     struct nbrec_logical_port **new_ports = xmalloc(sizeof *new_ports *
545                                                     (lswitch->n_ports + 1));
546     memcpy(new_ports, lswitch->ports, sizeof *new_ports * lswitch->n_ports);
547     new_ports[lswitch->n_ports] = lport;
548     nbrec_logical_switch_set_ports(lswitch, new_ports, lswitch->n_ports + 1);
549     free(new_ports);
550 }
551
552 /* Removes lport 'lswitch->ports[idx]'. */
553 static void
554 remove_lport(const struct nbrec_logical_switch *lswitch, size_t idx)
555 {
556     const struct nbrec_logical_port *lport = lswitch->ports[idx];
557
558     /* First remove 'lport' from the array of ports.  This is what will
559      * actually cause the logical port to be deleted when the transaction is
560      * sent to the database server (due to garbage collection). */
561     struct nbrec_logical_port **new_ports
562         = xmemdup(lswitch->ports, sizeof *new_ports * lswitch->n_ports);
563     new_ports[idx] = new_ports[lswitch->n_ports - 1];
564     nbrec_logical_switch_verify_ports(lswitch);
565     nbrec_logical_switch_set_ports(lswitch, new_ports, lswitch->n_ports - 1);
566     free(new_ports);
567
568     /* Delete 'lport' from the IDL.  This won't have a real effect on the
569      * database server (the IDL will suppress it in fact) but it means that it
570      * won't show up when we iterate with NBREC_LOGICAL_PORT_FOR_EACH later. */
571     nbrec_logical_port_delete(lport);
572 }
573
574 static void
575 nbctl_lport_del(struct ctl_context *ctx)
576 {
577     const struct nbrec_logical_port *lport;
578
579     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
580     if (!lport) {
581         return;
582     }
583
584     /* Find the switch that contains 'lport', then delete it. */
585     const struct nbrec_logical_switch *lswitch;
586     NBREC_LOGICAL_SWITCH_FOR_EACH (lswitch, ctx->idl) {
587         for (size_t i = 0; i < lswitch->n_ports; i++) {
588             if (lswitch->ports[i] == lport) {
589                 remove_lport(lswitch, i);
590                 return;
591             }
592         }
593     }
594
595     VLOG_WARN("logical port %s is not part of any logical switch",
596               ctx->argv[1]);
597 }
598
599 static void
600 nbctl_lport_list(struct ctl_context *ctx)
601 {
602     const char *id = ctx->argv[1];
603     const struct nbrec_logical_switch *lswitch;
604     struct smap lports;
605     size_t i;
606
607     lswitch = lswitch_by_name_or_uuid(ctx, id);
608     if (!lswitch) {
609         return;
610     }
611
612     smap_init(&lports);
613     for (i = 0; i < lswitch->n_ports; i++) {
614         const struct nbrec_logical_port *lport = lswitch->ports[i];
615         smap_add_format(&lports, lport->name, UUID_FMT " (%s)",
616                         UUID_ARGS(&lport->header_.uuid), lport->name);
617     }
618     const struct smap_node **nodes = smap_sort(&lports);
619     for (i = 0; i < smap_count(&lports); i++) {
620         const struct smap_node *node = nodes[i];
621         ds_put_format(&ctx->output, "%s\n", node->value);
622     }
623     smap_destroy(&lports);
624     free(nodes);
625 }
626
627 static void
628 nbctl_lport_get_parent(struct ctl_context *ctx)
629 {
630     const struct nbrec_logical_port *lport;
631
632     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
633     if (!lport) {
634         return;
635     }
636
637     if (lport->parent_name) {
638         ds_put_format(&ctx->output, "%s\n", lport->parent_name);
639     }
640 }
641
642 static void
643 nbctl_lport_get_tag(struct ctl_context *ctx)
644 {
645     const struct nbrec_logical_port *lport;
646
647     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
648     if (!lport) {
649         return;
650     }
651
652     if (lport->n_tag > 0) {
653         ds_put_format(&ctx->output, "%"PRId64"\n", lport->tag[0]);
654     }
655 }
656
657 static void
658 nbctl_lport_set_addresses(struct ctl_context *ctx)
659 {
660     const char *id = ctx->argv[1];
661     const struct nbrec_logical_port *lport;
662
663     lport = lport_by_name_or_uuid(ctx, id);
664     if (!lport) {
665         return;
666     }
667
668     nbrec_logical_port_set_addresses(lport,
669             (const char **) ctx->argv + 2, ctx->argc - 2);
670 }
671
672 static void
673 nbctl_lport_get_addresses(struct ctl_context *ctx)
674 {
675     const char *id = ctx->argv[1];
676     const struct nbrec_logical_port *lport;
677     struct svec addresses;
678     const char *mac;
679     size_t i;
680
681     lport = lport_by_name_or_uuid(ctx, id);
682     if (!lport) {
683         return;
684     }
685
686     svec_init(&addresses);
687     for (i = 0; i < lport->n_addresses; i++) {
688         svec_add(&addresses, lport->addresses[i]);
689     }
690     svec_sort(&addresses);
691     SVEC_FOR_EACH(i, mac, &addresses) {
692         ds_put_format(&ctx->output, "%s\n", mac);
693     }
694     svec_destroy(&addresses);
695 }
696
697 static void
698 nbctl_lport_set_port_security(struct ctl_context *ctx)
699 {
700     const char *id = ctx->argv[1];
701     const struct nbrec_logical_port *lport;
702
703     lport = lport_by_name_or_uuid(ctx, id);
704     if (!lport) {
705         return;
706     }
707
708     nbrec_logical_port_set_port_security(lport,
709             (const char **) ctx->argv + 2, ctx->argc - 2);
710 }
711
712 static void
713 nbctl_lport_get_port_security(struct ctl_context *ctx)
714 {
715     const char *id = ctx->argv[1];
716     const struct nbrec_logical_port *lport;
717     struct svec addrs;
718     const char *addr;
719     size_t i;
720
721     lport = lport_by_name_or_uuid(ctx, id);
722     if (!lport) {
723         return;
724     }
725
726     svec_init(&addrs);
727     for (i = 0; i < lport->n_port_security; i++) {
728         svec_add(&addrs, lport->port_security[i]);
729     }
730     svec_sort(&addrs);
731     SVEC_FOR_EACH(i, addr, &addrs) {
732         ds_put_format(&ctx->output, "%s\n", addr);
733     }
734     svec_destroy(&addrs);
735 }
736
737 static void
738 nbctl_lport_get_up(struct ctl_context *ctx)
739 {
740     const char *id = ctx->argv[1];
741     const struct nbrec_logical_port *lport;
742
743     lport = lport_by_name_or_uuid(ctx, id);
744     if (!lport) {
745         return;
746     }
747
748     ds_put_format(&ctx->output,
749                   "%s\n", (lport->up && *lport->up) ? "up" : "down");
750 }
751
752 static void
753 nbctl_lport_set_enabled(struct ctl_context *ctx)
754 {
755     const char *id = ctx->argv[1];
756     const char *state = ctx->argv[2];
757     const struct nbrec_logical_port *lport;
758
759     lport = lport_by_name_or_uuid(ctx, id);
760     if (!lport) {
761         return;
762     }
763
764     if (!strcasecmp(state, "enabled")) {
765         bool enabled = true;
766         nbrec_logical_port_set_enabled(lport, &enabled, 1);
767     } else if (!strcasecmp(state, "disabled")) {
768         bool enabled = false;
769         nbrec_logical_port_set_enabled(lport, &enabled, 1);
770     } else {
771         VLOG_ERR("Invalid state '%s' provided to lport-set-enabled", state);
772     }
773 }
774
775 static void
776 nbctl_lport_get_enabled(struct ctl_context *ctx)
777 {
778     const char *id = ctx->argv[1];
779     const struct nbrec_logical_port *lport;
780
781     lport = lport_by_name_or_uuid(ctx, id);
782     if (!lport) {
783         return;
784     }
785
786     ds_put_format(&ctx->output, "%s\n",
787                   !lport->enabled || *lport->enabled ? "enabled" : "disabled");
788 }
789
790 static void
791 nbctl_lport_set_type(struct ctl_context *ctx)
792 {
793     const char *id = ctx->argv[1];
794     const char *type = ctx->argv[2];
795     const struct nbrec_logical_port *lport;
796
797     lport = lport_by_name_or_uuid(ctx, id);
798     if (!lport) {
799         return;
800     }
801
802     nbrec_logical_port_set_type(lport, type);
803 }
804
805 static void
806 nbctl_lport_get_type(struct ctl_context *ctx)
807 {
808     const char *id = ctx->argv[1];
809     const struct nbrec_logical_port *lport;
810
811     lport = lport_by_name_or_uuid(ctx, id);
812     if (!lport) {
813         return;
814     }
815
816     ds_put_format(&ctx->output, "%s\n", lport->type);
817 }
818
819 static void
820 nbctl_lport_set_options(struct ctl_context *ctx)
821 {
822     const char *id = ctx->argv[1];
823     const struct nbrec_logical_port *lport;
824     size_t i;
825     struct smap options = SMAP_INITIALIZER(&options);
826
827     lport = lport_by_name_or_uuid(ctx, id);
828     if (!lport) {
829         return;
830     }
831
832     for (i = 2; i < ctx->argc; i++) {
833         char *key, *value;
834         value = xstrdup(ctx->argv[i]);
835         key = strsep(&value, "=");
836         if (value) {
837             smap_add(&options, key, value);
838         }
839         free(key);
840     }
841
842     nbrec_logical_port_set_options(lport, &options);
843
844     smap_destroy(&options);
845 }
846
847 static void
848 nbctl_lport_get_options(struct ctl_context *ctx)
849 {
850     const char *id = ctx->argv[1];
851     const struct nbrec_logical_port *lport;
852     struct smap_node *node;
853
854     lport = lport_by_name_or_uuid(ctx, id);
855     if (!lport) {
856         return;
857     }
858
859     SMAP_FOR_EACH(node, &lport->options) {
860         ds_put_format(&ctx->output, "%s=%s\n", node->key, node->value);
861     }
862 }
863
864 enum {
865     DIR_FROM_LPORT,
866     DIR_TO_LPORT
867 };
868
869 static int
870 dir_encode(const char *dir)
871 {
872     if (!strcmp(dir, "from-lport")) {
873         return DIR_FROM_LPORT;
874     } else if (!strcmp(dir, "to-lport")) {
875         return DIR_TO_LPORT;
876     }
877
878     OVS_NOT_REACHED();
879 }
880
881 static int
882 acl_cmp(const void *acl1_, const void *acl2_)
883 {
884     const struct nbrec_acl *const *acl1p = acl1_;
885     const struct nbrec_acl *const *acl2p = acl2_;
886     const struct nbrec_acl *acl1 = *acl1p;
887     const struct nbrec_acl *acl2 = *acl2p;
888
889     int dir1 = dir_encode(acl1->direction);
890     int dir2 = dir_encode(acl2->direction);
891
892     if (dir1 != dir2) {
893         return dir1 < dir2 ? -1 : 1;
894     } else if (acl1->priority != acl2->priority) {
895         return acl1->priority > acl2->priority ? -1 : 1;
896     } else {
897         return strcmp(acl1->match, acl2->match);
898     }
899 }
900
901 static void
902 nbctl_acl_list(struct ctl_context *ctx)
903 {
904     const struct nbrec_logical_switch *lswitch;
905     const struct nbrec_acl **acls;
906     size_t i;
907
908     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
909     if (!lswitch) {
910         return;
911     }
912
913     acls = xmalloc(sizeof *acls * lswitch->n_acls);
914     for (i = 0; i < lswitch->n_acls; i++) {
915         acls[i] = lswitch->acls[i];
916     }
917
918     qsort(acls, lswitch->n_acls, sizeof *acls, acl_cmp);
919
920     for (i = 0; i < lswitch->n_acls; i++) {
921         const struct nbrec_acl *acl = acls[i];
922         printf("%10s %5"PRId64" (%s) %s%s\n", acl->direction, acl->priority,
923                 acl->match, acl->action, acl->log ? " log" : "");
924     }
925
926     free(acls);
927 }
928
929 static void
930 nbctl_acl_add(struct ctl_context *ctx)
931 {
932     const struct nbrec_logical_switch *lswitch;
933     const char *action = ctx->argv[5];
934     const char *direction;
935     int64_t priority;
936
937     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
938     if (!lswitch) {
939         return;
940     }
941
942     /* Validate direction.  Only require the first letter. */
943     if (ctx->argv[2][0] == 't') {
944         direction = "to-lport";
945     } else if (ctx->argv[2][0] == 'f') {
946         direction = "from-lport";
947     } else {
948         VLOG_WARN("Invalid direction '%s'", ctx->argv[2]);
949         return;
950     }
951
952     /* Validate priority. */
953     if (!ovs_scan(ctx->argv[3], "%"SCNd64, &priority) || priority < 0
954         || priority > 32767) {
955         VLOG_WARN("Invalid priority '%s'", ctx->argv[3]);
956         return;
957     }
958
959     /* Validate action. */
960     if (strcmp(action, "allow") && strcmp(action, "allow-related")
961         && strcmp(action, "drop") && strcmp(action, "reject")) {
962         VLOG_WARN("Invalid action '%s'", action);
963         return;
964     }
965
966     /* Create the acl. */
967     struct nbrec_acl *acl = nbrec_acl_insert(ctx->txn);
968     nbrec_acl_set_priority(acl, priority);
969     nbrec_acl_set_direction(acl, direction);
970     nbrec_acl_set_match(acl, ctx->argv[4]);
971     nbrec_acl_set_action(acl, action);
972     if (shash_find(&ctx->options, "--log") != NULL) {
973         nbrec_acl_set_log(acl, true);
974     }
975
976     /* Insert the acl into the logical switch. */
977     nbrec_logical_switch_verify_acls(lswitch);
978     struct nbrec_acl **new_acls = xmalloc(sizeof *new_acls *
979                                           (lswitch->n_acls + 1));
980     memcpy(new_acls, lswitch->acls, sizeof *new_acls * lswitch->n_acls);
981     new_acls[lswitch->n_acls] = acl;
982     nbrec_logical_switch_set_acls(lswitch, new_acls, lswitch->n_acls + 1);
983     free(new_acls);
984 }
985
986 static void
987 nbctl_acl_del(struct ctl_context *ctx)
988 {
989     const struct nbrec_logical_switch *lswitch;
990     const char *direction;
991     int64_t priority = 0;
992
993     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
994     if (!lswitch) {
995         return;
996     }
997
998     if (ctx->argc != 2 && ctx->argc != 3 && ctx->argc != 5) {
999         VLOG_WARN("Invalid number of arguments");
1000         return;
1001     }
1002
1003     if (ctx->argc == 2) {
1004         /* If direction, priority, and match are not specified, delete
1005          * all ACLs. */
1006         nbrec_logical_switch_verify_acls(lswitch);
1007         nbrec_logical_switch_set_acls(lswitch, NULL, 0);
1008         return;
1009     }
1010
1011     /* Validate direction.  Only require first letter. */
1012     if (ctx->argv[2][0] == 't') {
1013         direction = "to-lport";
1014     } else if (ctx->argv[2][0] == 'f') {
1015         direction = "from-lport";
1016     } else {
1017         VLOG_WARN("Invalid direction '%s'", ctx->argv[2]);
1018         return;
1019     }
1020
1021     /* If priority and match are not specified, delete all ACLs with the
1022      * specified direction. */
1023     if (ctx->argc == 3) {
1024         struct nbrec_acl **new_acls
1025             = xmalloc(sizeof *new_acls * lswitch->n_acls);
1026
1027         int n_acls = 0;
1028         for (size_t i = 0; i < lswitch->n_acls; i++) {
1029             if (strcmp(direction, lswitch->acls[i]->direction)) {
1030                 new_acls[n_acls++] = lswitch->acls[i];
1031             }
1032         }
1033
1034         nbrec_logical_switch_verify_acls(lswitch);
1035         nbrec_logical_switch_set_acls(lswitch, new_acls, n_acls);
1036         free(new_acls);
1037         return;
1038     }
1039
1040     /* Validate priority. */
1041     if (!ovs_scan(ctx->argv[3], "%"SCNd64, &priority) || priority < 0
1042         || priority > 32767) {
1043         VLOG_WARN("Invalid priority '%s'", ctx->argv[3]);
1044         return;
1045     }
1046
1047     /* Remove the matching rule. */
1048     for (size_t i = 0; i < lswitch->n_acls; i++) {
1049         struct nbrec_acl *acl = lswitch->acls[i];
1050
1051         if (priority == acl->priority && !strcmp(ctx->argv[4], acl->match) &&
1052              !strcmp(direction, acl->direction)) {
1053             struct nbrec_acl **new_acls
1054                 = xmemdup(lswitch->acls, sizeof *new_acls * lswitch->n_acls);
1055             new_acls[i] = lswitch->acls[lswitch->n_acls - 1];
1056             nbrec_logical_switch_verify_acls(lswitch);
1057             nbrec_logical_switch_set_acls(lswitch, new_acls,
1058                                           lswitch->n_acls - 1);
1059             free(new_acls);
1060             return;
1061         }
1062     }
1063 }
1064 \f
1065 static const struct ctl_table_class tables[] = {
1066     {&nbrec_table_logical_switch,
1067      {{&nbrec_table_logical_switch, &nbrec_logical_switch_col_name, NULL},
1068       {NULL, NULL, NULL}}},
1069
1070     {&nbrec_table_logical_port,
1071      {{&nbrec_table_logical_port, &nbrec_logical_port_col_name, NULL},
1072       {NULL, NULL, NULL}}},
1073
1074     {&nbrec_table_acl,
1075      {{NULL, NULL, NULL},
1076       {NULL, NULL, NULL}}},
1077
1078     {&nbrec_table_logical_router,
1079      {{&nbrec_table_logical_router, &nbrec_logical_router_col_name, NULL},
1080       {NULL, NULL, NULL}}},
1081
1082     {&nbrec_table_logical_router_port,
1083      {{&nbrec_table_logical_router_port, &nbrec_logical_router_port_col_name,
1084        NULL},
1085       {NULL, NULL, NULL}}},
1086
1087     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1088 };
1089 \f
1090 static void
1091 run_prerequisites(struct ctl_command *commands, size_t n_commands,
1092                   struct ovsdb_idl *idl)
1093 {
1094     struct ctl_command *c;
1095
1096     for (c = commands; c < &commands[n_commands]; c++) {
1097         if (c->syntax->prerequisites) {
1098             struct ctl_context ctx;
1099
1100             ds_init(&c->output);
1101             c->table = NULL;
1102
1103             ctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
1104             (c->syntax->prerequisites)(&ctx);
1105             ctl_context_done(&ctx, c);
1106
1107             ovs_assert(!c->output.string);
1108             ovs_assert(!c->table);
1109         }
1110     }
1111 }
1112
1113 static void
1114 do_nbctl(const char *args, struct ctl_command *commands, size_t n_commands,
1115          struct ovsdb_idl *idl)
1116 {
1117     struct ovsdb_idl_txn *txn;
1118     enum ovsdb_idl_txn_status status;
1119     struct ovsdb_symbol_table *symtab;
1120     struct ctl_context ctx;
1121     struct ctl_command *c;
1122     struct shash_node *node;
1123     char *error = NULL;
1124
1125     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
1126     if (dry_run) {
1127         ovsdb_idl_txn_set_dry_run(txn);
1128     }
1129
1130     ovsdb_idl_txn_add_comment(txn, "ovs-nbctl: %s", args);
1131
1132     symtab = ovsdb_symbol_table_create();
1133     for (c = commands; c < &commands[n_commands]; c++) {
1134         ds_init(&c->output);
1135         c->table = NULL;
1136     }
1137     ctl_context_init(&ctx, NULL, idl, txn, symtab, NULL);
1138     for (c = commands; c < &commands[n_commands]; c++) {
1139         ctl_context_init_command(&ctx, c);
1140         if (c->syntax->run) {
1141             (c->syntax->run)(&ctx);
1142         }
1143         ctl_context_done_command(&ctx, c);
1144
1145         if (ctx.try_again) {
1146             ctl_context_done(&ctx, NULL);
1147             goto try_again;
1148         }
1149     }
1150     ctl_context_done(&ctx, NULL);
1151
1152     SHASH_FOR_EACH (node, &symtab->sh) {
1153         struct ovsdb_symbol *symbol = node->data;
1154         if (!symbol->created) {
1155             ctl_fatal("row id \"%s\" is referenced but never created (e.g. "
1156                       "with \"-- --id=%s create ...\")",
1157                       node->name, node->name);
1158         }
1159         if (!symbol->strong_ref) {
1160             if (!symbol->weak_ref) {
1161                 VLOG_WARN("row id \"%s\" was created but no reference to it "
1162                           "was inserted, so it will not actually appear in "
1163                           "the database", node->name);
1164             } else {
1165                 VLOG_WARN("row id \"%s\" was created but only a weak "
1166                           "reference to it was inserted, so it will not "
1167                           "actually appear in the database", node->name);
1168             }
1169         }
1170     }
1171
1172     status = ovsdb_idl_txn_commit_block(txn);
1173     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
1174         for (c = commands; c < &commands[n_commands]; c++) {
1175             if (c->syntax->postprocess) {
1176                 ctl_context_init(&ctx, c, idl, txn, symtab, NULL);
1177                 (c->syntax->postprocess)(&ctx);
1178                 ctl_context_done(&ctx, c);
1179             }
1180         }
1181     }
1182     error = xstrdup(ovsdb_idl_txn_get_error(txn));
1183
1184     switch (status) {
1185     case TXN_UNCOMMITTED:
1186     case TXN_INCOMPLETE:
1187         OVS_NOT_REACHED();
1188
1189     case TXN_ABORTED:
1190         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
1191         ctl_fatal("transaction aborted");
1192
1193     case TXN_UNCHANGED:
1194     case TXN_SUCCESS:
1195         break;
1196
1197     case TXN_TRY_AGAIN:
1198         goto try_again;
1199
1200     case TXN_ERROR:
1201         ctl_fatal("transaction error: %s", error);
1202
1203     case TXN_NOT_LOCKED:
1204         /* Should not happen--we never call ovsdb_idl_set_lock(). */
1205         ctl_fatal("database not locked");
1206
1207     default:
1208         OVS_NOT_REACHED();
1209     }
1210     free(error);
1211
1212     ovsdb_symbol_table_destroy(symtab);
1213
1214     for (c = commands; c < &commands[n_commands]; c++) {
1215         struct ds *ds = &c->output;
1216
1217         if (c->table) {
1218             table_print(c->table, &table_style);
1219         } else if (oneline) {
1220             size_t j;
1221
1222             ds_chomp(ds, '\n');
1223             for (j = 0; j < ds->length; j++) {
1224                 int ch = ds->string[j];
1225                 switch (ch) {
1226                 case '\n':
1227                     fputs("\\n", stdout);
1228                     break;
1229
1230                 case '\\':
1231                     fputs("\\\\", stdout);
1232                     break;
1233
1234                 default:
1235                     putchar(ch);
1236                 }
1237             }
1238             putchar('\n');
1239         } else {
1240             fputs(ds_cstr(ds), stdout);
1241         }
1242         ds_destroy(&c->output);
1243         table_destroy(c->table);
1244         free(c->table);
1245
1246         shash_destroy_free_data(&c->options);
1247     }
1248     free(commands);
1249     ovsdb_idl_txn_destroy(txn);
1250     ovsdb_idl_destroy(idl);
1251
1252     exit(EXIT_SUCCESS);
1253
1254 try_again:
1255     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
1256      * resources and return so that the caller can try again. */
1257     if (txn) {
1258         ovsdb_idl_txn_abort(txn);
1259         ovsdb_idl_txn_destroy(txn);
1260         the_idl_txn = NULL;
1261     }
1262     ovsdb_symbol_table_destroy(symtab);
1263     for (c = commands; c < &commands[n_commands]; c++) {
1264         ds_destroy(&c->output);
1265         table_destroy(c->table);
1266         free(c->table);
1267     }
1268     free(error);
1269 }
1270
1271 /* Frees the current transaction and the underlying IDL and then calls
1272  * exit(status).
1273  *
1274  * Freeing the transaction and the IDL is not strictly necessary, but it makes
1275  * for a clean memory leak report from valgrind in the normal case.  That makes
1276  * it easier to notice real memory leaks. */
1277 static void
1278 nbctl_exit(int status)
1279 {
1280     if (the_idl_txn) {
1281         ovsdb_idl_txn_abort(the_idl_txn);
1282         ovsdb_idl_txn_destroy(the_idl_txn);
1283     }
1284     ovsdb_idl_destroy(the_idl);
1285     exit(status);
1286 }
1287
1288 static const struct ctl_command_syntax nbctl_commands[] = {
1289     { "show", 0, 1, "[LSWITCH]", NULL, nbctl_show, NULL, "", RO },
1290
1291     /* lswitch commands. */
1292     { "lswitch-add", 0, 1, "[LSWITCH]", NULL, nbctl_lswitch_add,
1293       NULL, "", RW },
1294     { "lswitch-del", 1, 1, "LSWITCH", NULL, nbctl_lswitch_del,
1295       NULL, "", RW },
1296     { "lswitch-list", 0, 0, "", NULL, nbctl_lswitch_list, NULL, "", RO },
1297
1298     /* acl commands. */
1299     { "acl-add", 5, 5, "LSWITCH DIRECTION PRIORITY MATCH ACTION", NULL,
1300       nbctl_acl_add, NULL, "--log", RW },
1301     { "acl-del", 1, 4, "LSWITCH [DIRECTION [PRIORITY MATCH]]", NULL,
1302       nbctl_acl_del, NULL, "", RW },
1303     { "acl-list", 1, 1, "LSWITCH", NULL, nbctl_acl_list, NULL, "", RO },
1304
1305     /* lport commands. */
1306     { "lport-add", 2, 4, "LSWITCH LPORT [PARENT] [TAG]", NULL, nbctl_lport_add,
1307       NULL, "", RW },
1308     { "lport-del", 1, 1, "LPORT", NULL, nbctl_lport_del, NULL, "", RO },
1309     { "lport-list", 1, 1, "LSWITCH", NULL, nbctl_lport_list, NULL, "", RO },
1310     { "lport-get-parent", 1, 1, "LPORT", NULL, nbctl_lport_get_parent, NULL,
1311       "", RO },
1312     { "lport-get-tag", 1, 1, "LPORT", NULL, nbctl_lport_get_tag, NULL, "",
1313       RO },
1314     { "lport-set-addresses", 1, INT_MAX, "LPORT [ADDRESS]...", NULL,
1315       nbctl_lport_set_addresses, NULL, "", RW },
1316     { "lport-get-addresses", 1, 1, "LPORT", NULL,
1317       nbctl_lport_get_addresses, NULL,
1318       "", RO },
1319     { "lport-set-port-security", 0, INT_MAX, "LPORT [ADDRS]...", NULL,
1320       nbctl_lport_set_port_security, NULL, "", RW },
1321     { "lport-get-port-security", 1, 1, "LPORT", NULL,
1322       nbctl_lport_get_port_security, NULL, "", RO },
1323     { "lport-get-up", 1, 1, "LPORT", NULL, nbctl_lport_get_up, NULL, "", RO },
1324     { "lport-set-enabled", 2, 2, "LPORT STATE", NULL, nbctl_lport_set_enabled,
1325       NULL, "", RW },
1326     { "lport-get-enabled", 1, 1, "LPORT", NULL, nbctl_lport_get_enabled, NULL,
1327       "", RO },
1328     { "lport-set-type", 2, 2, "LPORT TYPE", NULL, nbctl_lport_set_type, NULL,
1329       "", RW },
1330     { "lport-get-type", 1, 1, "LPORT", NULL, nbctl_lport_get_type, NULL, "",
1331       RO },
1332     { "lport-set-options", 1, INT_MAX, "LPORT KEY=VALUE [KEY=VALUE]...", NULL,
1333       nbctl_lport_set_options, NULL, "", RW },
1334     { "lport-get-options", 1, 1, "LPORT", NULL, nbctl_lport_get_options, NULL,
1335       "", RO },
1336
1337     {NULL, 0, 0, NULL, NULL, NULL, NULL, "", RO},
1338 };
1339
1340 /* Registers nbctl and common db commands. */
1341 static void
1342 nbctl_cmd_init(void)
1343 {
1344     ctl_init(tables, NULL, nbctl_exit);
1345     ctl_register_commands(nbctl_commands);
1346 }