ovn-northd: Can't use ct() for router ports.
[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 Options:\n\
334   --db=DATABASE               connect to DATABASE\n\
335                               (default: %s)\n\
336   -t, --timeout=SECS          wait at most SECS seconds\n\
337   --dry-run                   do not commit changes to database\n\
338   --oneline                   print exactly one line of output per command\n",
339            program_name, program_name, nbctl_default_db());
340     vlog_usage();
341     printf("\
342   --no-syslog             equivalent to --verbose=nbctl:syslog:warn\n");
343     printf("\n\
344 Other options:\n\
345   -h, --help                  display this help message\n\
346   -V, --version               display version information\n");
347     exit(EXIT_SUCCESS);
348 }
349 \f
350 static const struct nbrec_logical_switch *
351 lswitch_by_name_or_uuid(struct ctl_context *ctx, const char *id)
352 {
353     const struct nbrec_logical_switch *lswitch = NULL;
354     bool is_uuid = false;
355     bool duplicate = false;
356     struct uuid lswitch_uuid;
357
358     if (uuid_from_string(&lswitch_uuid, id)) {
359         is_uuid = true;
360         lswitch = nbrec_logical_switch_get_for_uuid(ctx->idl,
361                                                     &lswitch_uuid);
362     }
363
364     if (!lswitch) {
365         const struct nbrec_logical_switch *iter;
366
367         NBREC_LOGICAL_SWITCH_FOR_EACH(iter, ctx->idl) {
368             if (strcmp(iter->name, id)) {
369                 continue;
370             }
371             if (lswitch) {
372                 VLOG_WARN("There is more than one logical switch named '%s'. "
373                         "Use a UUID.", id);
374                 lswitch = NULL;
375                 duplicate = true;
376                 break;
377             }
378             lswitch = iter;
379         }
380     }
381
382     if (!lswitch && !duplicate) {
383         VLOG_WARN("lswitch not found for %s: '%s'",
384                 is_uuid ? "UUID" : "name", id);
385     }
386
387     return lswitch;
388 }
389
390 static void
391 print_lswitch(const struct nbrec_logical_switch *lswitch, struct ds *s)
392 {
393     ds_put_format(s, "    lswitch "UUID_FMT" (%s)\n",
394                   UUID_ARGS(&lswitch->header_.uuid), lswitch->name);
395
396     for (size_t i = 0; i < lswitch->n_ports; i++) {
397         const struct nbrec_logical_port *lport = lswitch->ports[i];
398
399         ds_put_format(s, "        lport %s\n", lport->name);
400         if (lport->parent_name) {
401             ds_put_format(s, "            parent: %s\n", lport->parent_name);
402         }
403         if (lport->n_tag) {
404             ds_put_format(s, "            tag: %"PRIu64"\n", lport->tag[0]);
405         }
406         if (lport->n_addresses) {
407             ds_put_cstr(s, "            addresses:");
408             for (size_t j = 0; j < lport->n_addresses; j++) {
409                 ds_put_format(s, " %s", lport->addresses[j]);
410             }
411             ds_put_char(s, '\n');
412         }
413     }
414 }
415
416 static void
417 nbctl_show(struct ctl_context *ctx)
418 {
419     const struct nbrec_logical_switch *lswitch;
420
421     if (ctx->argc == 2) {
422         lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
423         if (lswitch) {
424             print_lswitch(lswitch, &ctx->output);
425         }
426     } else {
427         NBREC_LOGICAL_SWITCH_FOR_EACH(lswitch, ctx->idl) {
428             print_lswitch(lswitch, &ctx->output);
429         }
430     }
431 }
432
433 static void
434 nbctl_lswitch_add(struct ctl_context *ctx)
435 {
436     struct nbrec_logical_switch *lswitch;
437
438     lswitch = nbrec_logical_switch_insert(ctx->txn);
439     if (ctx->argc == 2) {
440         nbrec_logical_switch_set_name(lswitch, ctx->argv[1]);
441     }
442 }
443
444 static void
445 nbctl_lswitch_del(struct ctl_context *ctx)
446 {
447     const char *id = ctx->argv[1];
448     const struct nbrec_logical_switch *lswitch;
449
450     lswitch = lswitch_by_name_or_uuid(ctx, id);
451     if (!lswitch) {
452         return;
453     }
454
455     nbrec_logical_switch_delete(lswitch);
456 }
457
458 static void
459 nbctl_lswitch_list(struct ctl_context *ctx)
460 {
461     const struct nbrec_logical_switch *lswitch;
462     struct smap lswitches;
463
464     smap_init(&lswitches);
465     NBREC_LOGICAL_SWITCH_FOR_EACH(lswitch, ctx->idl) {
466         smap_add_format(&lswitches, lswitch->name, UUID_FMT " (%s)",
467                         UUID_ARGS(&lswitch->header_.uuid), lswitch->name);
468     }
469     const struct smap_node **nodes = smap_sort(&lswitches);
470     for (size_t i = 0; i < smap_count(&lswitches); i++) {
471         const struct smap_node *node = nodes[i];
472         ds_put_format(&ctx->output, "%s\n", node->value);
473     }
474     smap_destroy(&lswitches);
475     free(nodes);
476 }
477 \f
478 static const struct nbrec_logical_port *
479 lport_by_name_or_uuid(struct ctl_context *ctx, const char *id)
480 {
481     const struct nbrec_logical_port *lport = NULL;
482     bool is_uuid = false;
483     struct uuid lport_uuid;
484
485     if (uuid_from_string(&lport_uuid, id)) {
486         is_uuid = true;
487         lport = nbrec_logical_port_get_for_uuid(ctx->idl, &lport_uuid);
488     }
489
490     if (!lport) {
491         NBREC_LOGICAL_PORT_FOR_EACH(lport, ctx->idl) {
492             if (!strcmp(lport->name, id)) {
493                 break;
494             }
495         }
496     }
497
498     if (!lport) {
499         VLOG_WARN("lport not found for %s: '%s'",
500                 is_uuid ? "UUID" : "name", id);
501     }
502
503     return lport;
504 }
505
506 static void
507 nbctl_lport_add(struct ctl_context *ctx)
508 {
509     struct nbrec_logical_port *lport;
510     const struct nbrec_logical_switch *lswitch;
511     int64_t tag;
512
513     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
514     if (!lswitch) {
515         return;
516     }
517
518     if (ctx->argc != 3 && ctx->argc != 5) {
519         /* If a parent_name is specified, a tag must be specified as well. */
520         VLOG_WARN("Invalid arguments to lport-add.");
521         return;
522     }
523
524     if (ctx->argc == 5) {
525         /* Validate tag. */
526         if (!ovs_scan(ctx->argv[4], "%"SCNd64, &tag) || tag < 0 || tag > 4095) {
527             VLOG_WARN("Invalid tag '%s'", ctx->argv[4]);
528             return;
529         }
530     }
531
532     /* Create the logical port. */
533     lport = nbrec_logical_port_insert(ctx->txn);
534     nbrec_logical_port_set_name(lport, ctx->argv[2]);
535     if (ctx->argc == 5) {
536         nbrec_logical_port_set_parent_name(lport, ctx->argv[3]);
537         nbrec_logical_port_set_tag(lport, &tag, 1);
538     }
539
540     /* Insert the logical port into the logical switch. */
541     nbrec_logical_switch_verify_ports(lswitch);
542     struct nbrec_logical_port **new_ports = xmalloc(sizeof *new_ports *
543                                                     (lswitch->n_ports + 1));
544     memcpy(new_ports, lswitch->ports, sizeof *new_ports * lswitch->n_ports);
545     new_ports[lswitch->n_ports] = lport;
546     nbrec_logical_switch_set_ports(lswitch, new_ports, lswitch->n_ports + 1);
547     free(new_ports);
548 }
549
550 /* Removes lport 'lswitch->ports[idx]'. */
551 static void
552 remove_lport(const struct nbrec_logical_switch *lswitch, size_t idx)
553 {
554     const struct nbrec_logical_port *lport = lswitch->ports[idx];
555
556     /* First remove 'lport' from the array of ports.  This is what will
557      * actually cause the logical port to be deleted when the transaction is
558      * sent to the database server (due to garbage collection). */
559     struct nbrec_logical_port **new_ports
560         = xmemdup(lswitch->ports, sizeof *new_ports * lswitch->n_ports);
561     new_ports[idx] = new_ports[lswitch->n_ports - 1];
562     nbrec_logical_switch_verify_ports(lswitch);
563     nbrec_logical_switch_set_ports(lswitch, new_ports, lswitch->n_ports - 1);
564     free(new_ports);
565
566     /* Delete 'lport' from the IDL.  This won't have a real effect on the
567      * database server (the IDL will suppress it in fact) but it means that it
568      * won't show up when we iterate with NBREC_LOGICAL_PORT_FOR_EACH later. */
569     nbrec_logical_port_delete(lport);
570 }
571
572 static void
573 nbctl_lport_del(struct ctl_context *ctx)
574 {
575     const struct nbrec_logical_port *lport;
576
577     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
578     if (!lport) {
579         return;
580     }
581
582     /* Find the switch that contains 'lport', then delete it. */
583     const struct nbrec_logical_switch *lswitch;
584     NBREC_LOGICAL_SWITCH_FOR_EACH (lswitch, ctx->idl) {
585         for (size_t i = 0; i < lswitch->n_ports; i++) {
586             if (lswitch->ports[i] == lport) {
587                 remove_lport(lswitch, i);
588                 return;
589             }
590         }
591     }
592
593     VLOG_WARN("logical port %s is not part of any logical switch",
594               ctx->argv[1]);
595 }
596
597 static void
598 nbctl_lport_list(struct ctl_context *ctx)
599 {
600     const char *id = ctx->argv[1];
601     const struct nbrec_logical_switch *lswitch;
602     struct smap lports;
603     size_t i;
604
605     lswitch = lswitch_by_name_or_uuid(ctx, id);
606     if (!lswitch) {
607         return;
608     }
609
610     smap_init(&lports);
611     for (i = 0; i < lswitch->n_ports; i++) {
612         const struct nbrec_logical_port *lport = lswitch->ports[i];
613         smap_add_format(&lports, lport->name, UUID_FMT " (%s)",
614                         UUID_ARGS(&lport->header_.uuid), lport->name);
615     }
616     const struct smap_node **nodes = smap_sort(&lports);
617     for (i = 0; i < smap_count(&lports); i++) {
618         const struct smap_node *node = nodes[i];
619         ds_put_format(&ctx->output, "%s\n", node->value);
620     }
621     smap_destroy(&lports);
622     free(nodes);
623 }
624
625 static void
626 nbctl_lport_get_parent(struct ctl_context *ctx)
627 {
628     const struct nbrec_logical_port *lport;
629
630     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
631     if (!lport) {
632         return;
633     }
634
635     if (lport->parent_name) {
636         ds_put_format(&ctx->output, "%s\n", lport->parent_name);
637     }
638 }
639
640 static void
641 nbctl_lport_get_tag(struct ctl_context *ctx)
642 {
643     const struct nbrec_logical_port *lport;
644
645     lport = lport_by_name_or_uuid(ctx, ctx->argv[1]);
646     if (!lport) {
647         return;
648     }
649
650     if (lport->n_tag > 0) {
651         ds_put_format(&ctx->output, "%"PRId64"\n", lport->tag[0]);
652     }
653 }
654
655 static void
656 nbctl_lport_set_addresses(struct ctl_context *ctx)
657 {
658     const char *id = ctx->argv[1];
659     const struct nbrec_logical_port *lport;
660
661     lport = lport_by_name_or_uuid(ctx, id);
662     if (!lport) {
663         return;
664     }
665
666     nbrec_logical_port_set_addresses(lport,
667             (const char **) ctx->argv + 2, ctx->argc - 2);
668 }
669
670 static void
671 nbctl_lport_get_addresses(struct ctl_context *ctx)
672 {
673     const char *id = ctx->argv[1];
674     const struct nbrec_logical_port *lport;
675     struct svec addresses;
676     const char *mac;
677     size_t i;
678
679     lport = lport_by_name_or_uuid(ctx, id);
680     if (!lport) {
681         return;
682     }
683
684     svec_init(&addresses);
685     for (i = 0; i < lport->n_addresses; i++) {
686         svec_add(&addresses, lport->addresses[i]);
687     }
688     svec_sort(&addresses);
689     SVEC_FOR_EACH(i, mac, &addresses) {
690         ds_put_format(&ctx->output, "%s\n", mac);
691     }
692     svec_destroy(&addresses);
693 }
694
695 static void
696 nbctl_lport_set_port_security(struct ctl_context *ctx)
697 {
698     const char *id = ctx->argv[1];
699     const struct nbrec_logical_port *lport;
700
701     lport = lport_by_name_or_uuid(ctx, id);
702     if (!lport) {
703         return;
704     }
705
706     nbrec_logical_port_set_port_security(lport,
707             (const char **) ctx->argv + 2, ctx->argc - 2);
708 }
709
710 static void
711 nbctl_lport_get_port_security(struct ctl_context *ctx)
712 {
713     const char *id = ctx->argv[1];
714     const struct nbrec_logical_port *lport;
715     struct svec addrs;
716     const char *addr;
717     size_t i;
718
719     lport = lport_by_name_or_uuid(ctx, id);
720     if (!lport) {
721         return;
722     }
723
724     svec_init(&addrs);
725     for (i = 0; i < lport->n_port_security; i++) {
726         svec_add(&addrs, lport->port_security[i]);
727     }
728     svec_sort(&addrs);
729     SVEC_FOR_EACH(i, addr, &addrs) {
730         ds_put_format(&ctx->output, "%s\n", addr);
731     }
732     svec_destroy(&addrs);
733 }
734
735 static void
736 nbctl_lport_get_up(struct ctl_context *ctx)
737 {
738     const char *id = ctx->argv[1];
739     const struct nbrec_logical_port *lport;
740
741     lport = lport_by_name_or_uuid(ctx, id);
742     if (!lport) {
743         return;
744     }
745
746     ds_put_format(&ctx->output,
747                   "%s\n", (lport->up && *lport->up) ? "up" : "down");
748 }
749
750 static void
751 nbctl_lport_set_enabled(struct ctl_context *ctx)
752 {
753     const char *id = ctx->argv[1];
754     const char *state = ctx->argv[2];
755     const struct nbrec_logical_port *lport;
756
757     lport = lport_by_name_or_uuid(ctx, id);
758     if (!lport) {
759         return;
760     }
761
762     if (!strcasecmp(state, "enabled")) {
763         bool enabled = true;
764         nbrec_logical_port_set_enabled(lport, &enabled, 1);
765     } else if (!strcasecmp(state, "disabled")) {
766         bool enabled = false;
767         nbrec_logical_port_set_enabled(lport, &enabled, 1);
768     } else {
769         VLOG_ERR("Invalid state '%s' provided to lport-set-enabled", state);
770     }
771 }
772
773 static void
774 nbctl_lport_get_enabled(struct ctl_context *ctx)
775 {
776     const char *id = ctx->argv[1];
777     const struct nbrec_logical_port *lport;
778
779     lport = lport_by_name_or_uuid(ctx, id);
780     if (!lport) {
781         return;
782     }
783
784     ds_put_format(&ctx->output, "%s\n",
785                   !lport->enabled || *lport->enabled ? "enabled" : "disabled");
786 }
787
788 static void
789 nbctl_lport_set_type(struct ctl_context *ctx)
790 {
791     const char *id = ctx->argv[1];
792     const char *type = ctx->argv[2];
793     const struct nbrec_logical_port *lport;
794
795     lport = lport_by_name_or_uuid(ctx, id);
796     if (!lport) {
797         return;
798     }
799
800     nbrec_logical_port_set_type(lport, type);
801 }
802
803 static void
804 nbctl_lport_get_type(struct ctl_context *ctx)
805 {
806     const char *id = ctx->argv[1];
807     const struct nbrec_logical_port *lport;
808
809     lport = lport_by_name_or_uuid(ctx, id);
810     if (!lport) {
811         return;
812     }
813
814     ds_put_format(&ctx->output, "%s\n", lport->type);
815 }
816
817 static void
818 nbctl_lport_set_options(struct ctl_context *ctx)
819 {
820     const char *id = ctx->argv[1];
821     const struct nbrec_logical_port *lport;
822     size_t i;
823     struct smap options = SMAP_INITIALIZER(&options);
824
825     lport = lport_by_name_or_uuid(ctx, id);
826     if (!lport) {
827         return;
828     }
829
830     for (i = 2; i < ctx->argc; i++) {
831         char *key, *value;
832         value = xstrdup(ctx->argv[i]);
833         key = strsep(&value, "=");
834         if (value) {
835             smap_add(&options, key, value);
836         }
837         free(key);
838     }
839
840     nbrec_logical_port_set_options(lport, &options);
841
842     smap_destroy(&options);
843 }
844
845 static void
846 nbctl_lport_get_options(struct ctl_context *ctx)
847 {
848     const char *id = ctx->argv[1];
849     const struct nbrec_logical_port *lport;
850     struct smap_node *node;
851
852     lport = lport_by_name_or_uuid(ctx, id);
853     if (!lport) {
854         return;
855     }
856
857     SMAP_FOR_EACH(node, &lport->options) {
858         ds_put_format(&ctx->output, "%s=%s\n", node->key, node->value);
859     }
860 }
861
862 enum {
863     DIR_FROM_LPORT,
864     DIR_TO_LPORT
865 };
866
867 static int
868 dir_encode(const char *dir)
869 {
870     if (!strcmp(dir, "from-lport")) {
871         return DIR_FROM_LPORT;
872     } else if (!strcmp(dir, "to-lport")) {
873         return DIR_TO_LPORT;
874     }
875
876     OVS_NOT_REACHED();
877 }
878
879 static int
880 acl_cmp(const void *acl1_, const void *acl2_)
881 {
882     const struct nbrec_acl *const *acl1p = acl1_;
883     const struct nbrec_acl *const *acl2p = acl2_;
884     const struct nbrec_acl *acl1 = *acl1p;
885     const struct nbrec_acl *acl2 = *acl2p;
886
887     int dir1 = dir_encode(acl1->direction);
888     int dir2 = dir_encode(acl2->direction);
889
890     if (dir1 != dir2) {
891         return dir1 < dir2 ? -1 : 1;
892     } else if (acl1->priority != acl2->priority) {
893         return acl1->priority > acl2->priority ? -1 : 1;
894     } else {
895         return strcmp(acl1->match, acl2->match);
896     }
897 }
898
899 static void
900 nbctl_acl_list(struct ctl_context *ctx)
901 {
902     const struct nbrec_logical_switch *lswitch;
903     const struct nbrec_acl **acls;
904     size_t i;
905
906     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
907     if (!lswitch) {
908         return;
909     }
910
911     acls = xmalloc(sizeof *acls * lswitch->n_acls);
912     for (i = 0; i < lswitch->n_acls; i++) {
913         acls[i] = lswitch->acls[i];
914     }
915
916     qsort(acls, lswitch->n_acls, sizeof *acls, acl_cmp);
917
918     for (i = 0; i < lswitch->n_acls; i++) {
919         const struct nbrec_acl *acl = acls[i];
920         printf("%10s %5"PRId64" (%s) %s%s\n", acl->direction, acl->priority,
921                 acl->match, acl->action, acl->log ? " log" : "");
922     }
923
924     free(acls);
925 }
926
927 static void
928 nbctl_acl_add(struct ctl_context *ctx)
929 {
930     const struct nbrec_logical_switch *lswitch;
931     const char *action = ctx->argv[5];
932     const char *direction;
933     int64_t priority;
934
935     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
936     if (!lswitch) {
937         return;
938     }
939
940     /* Validate direction.  Only require the first letter. */
941     if (ctx->argv[2][0] == 't') {
942         direction = "to-lport";
943     } else if (ctx->argv[2][0] == 'f') {
944         direction = "from-lport";
945     } else {
946         VLOG_WARN("Invalid direction '%s'", ctx->argv[2]);
947         return;
948     }
949
950     /* Validate priority. */
951     if (!ovs_scan(ctx->argv[3], "%"SCNd64, &priority) || priority < 0
952         || priority > 32767) {
953         VLOG_WARN("Invalid priority '%s'", ctx->argv[3]);
954         return;
955     }
956
957     /* Validate action. */
958     if (strcmp(action, "allow") && strcmp(action, "allow-related")
959         && strcmp(action, "drop") && strcmp(action, "reject")) {
960         VLOG_WARN("Invalid action '%s'", action);
961         return;
962     }
963
964     /* Create the acl. */
965     struct nbrec_acl *acl = nbrec_acl_insert(ctx->txn);
966     nbrec_acl_set_priority(acl, priority);
967     nbrec_acl_set_direction(acl, direction);
968     nbrec_acl_set_match(acl, ctx->argv[4]);
969     nbrec_acl_set_action(acl, action);
970     if (shash_find(&ctx->options, "--log") != NULL) {
971         nbrec_acl_set_log(acl, true);
972     }
973
974     /* Insert the acl into the logical switch. */
975     nbrec_logical_switch_verify_acls(lswitch);
976     struct nbrec_acl **new_acls = xmalloc(sizeof *new_acls *
977                                           (lswitch->n_acls + 1));
978     memcpy(new_acls, lswitch->acls, sizeof *new_acls * lswitch->n_acls);
979     new_acls[lswitch->n_acls] = acl;
980     nbrec_logical_switch_set_acls(lswitch, new_acls, lswitch->n_acls + 1);
981     free(new_acls);
982 }
983
984 static void
985 nbctl_acl_del(struct ctl_context *ctx)
986 {
987     const struct nbrec_logical_switch *lswitch;
988     const char *direction;
989     int64_t priority = 0;
990
991     lswitch = lswitch_by_name_or_uuid(ctx, ctx->argv[1]);
992     if (!lswitch) {
993         return;
994     }
995
996     if (ctx->argc != 2 && ctx->argc != 3 && ctx->argc != 5) {
997         VLOG_WARN("Invalid number of arguments");
998         return;
999     }
1000
1001     if (ctx->argc == 2) {
1002         /* If direction, priority, and match are not specified, delete
1003          * all ACLs. */
1004         nbrec_logical_switch_verify_acls(lswitch);
1005         nbrec_logical_switch_set_acls(lswitch, NULL, 0);
1006         return;
1007     }
1008
1009     /* Validate direction.  Only require first letter. */
1010     if (ctx->argv[2][0] == 't') {
1011         direction = "to-lport";
1012     } else if (ctx->argv[2][0] == 'f') {
1013         direction = "from-lport";
1014     } else {
1015         VLOG_WARN("Invalid direction '%s'", ctx->argv[2]);
1016         return;
1017     }
1018
1019     /* If priority and match are not specified, delete all ACLs with the
1020      * specified direction. */
1021     if (ctx->argc == 3) {
1022         struct nbrec_acl **new_acls
1023             = xmalloc(sizeof *new_acls * lswitch->n_acls);
1024
1025         int n_acls = 0;
1026         for (size_t i = 0; i < lswitch->n_acls; i++) {
1027             if (strcmp(direction, lswitch->acls[i]->direction)) {
1028                 new_acls[n_acls++] = lswitch->acls[i];
1029             }
1030         }
1031
1032         nbrec_logical_switch_verify_acls(lswitch);
1033         nbrec_logical_switch_set_acls(lswitch, new_acls, n_acls);
1034         free(new_acls);
1035         return;
1036     }
1037
1038     /* Validate priority. */
1039     if (!ovs_scan(ctx->argv[3], "%"SCNd64, &priority) || priority < 0
1040         || priority > 32767) {
1041         VLOG_WARN("Invalid priority '%s'", ctx->argv[3]);
1042         return;
1043     }
1044
1045     /* Remove the matching rule. */
1046     for (size_t i = 0; i < lswitch->n_acls; i++) {
1047         struct nbrec_acl *acl = lswitch->acls[i];
1048
1049         if (priority == acl->priority && !strcmp(ctx->argv[4], acl->match) &&
1050              !strcmp(direction, acl->direction)) {
1051             struct nbrec_acl **new_acls
1052                 = xmemdup(lswitch->acls, sizeof *new_acls * lswitch->n_acls);
1053             new_acls[i] = lswitch->acls[lswitch->n_acls - 1];
1054             nbrec_logical_switch_verify_acls(lswitch);
1055             nbrec_logical_switch_set_acls(lswitch, new_acls,
1056                                           lswitch->n_acls - 1);
1057             free(new_acls);
1058             return;
1059         }
1060     }
1061 }
1062 \f
1063 static const struct ctl_table_class tables[] = {
1064     {&nbrec_table_logical_switch,
1065      {{&nbrec_table_logical_switch, &nbrec_logical_switch_col_name, NULL},
1066       {NULL, NULL, NULL}}},
1067
1068     {&nbrec_table_logical_port,
1069      {{&nbrec_table_logical_port, &nbrec_logical_port_col_name, NULL},
1070       {NULL, NULL, NULL}}},
1071
1072     {&nbrec_table_acl,
1073      {{NULL, NULL, NULL},
1074       {NULL, NULL, NULL}}},
1075
1076     {&nbrec_table_logical_router,
1077      {{&nbrec_table_logical_router, &nbrec_logical_router_col_name, NULL},
1078       {NULL, NULL, NULL}}},
1079
1080     {&nbrec_table_logical_router_port,
1081      {{&nbrec_table_logical_router_port, &nbrec_logical_router_port_col_name,
1082        NULL},
1083       {NULL, NULL, NULL}}},
1084
1085     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1086 };
1087 \f
1088 static void
1089 run_prerequisites(struct ctl_command *commands, size_t n_commands,
1090                   struct ovsdb_idl *idl)
1091 {
1092     struct ctl_command *c;
1093
1094     for (c = commands; c < &commands[n_commands]; c++) {
1095         if (c->syntax->prerequisites) {
1096             struct ctl_context ctx;
1097
1098             ds_init(&c->output);
1099             c->table = NULL;
1100
1101             ctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
1102             (c->syntax->prerequisites)(&ctx);
1103             ctl_context_done(&ctx, c);
1104
1105             ovs_assert(!c->output.string);
1106             ovs_assert(!c->table);
1107         }
1108     }
1109 }
1110
1111 static void
1112 do_nbctl(const char *args, struct ctl_command *commands, size_t n_commands,
1113          struct ovsdb_idl *idl)
1114 {
1115     struct ovsdb_idl_txn *txn;
1116     enum ovsdb_idl_txn_status status;
1117     struct ovsdb_symbol_table *symtab;
1118     struct ctl_context ctx;
1119     struct ctl_command *c;
1120     struct shash_node *node;
1121     char *error = NULL;
1122
1123     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
1124     if (dry_run) {
1125         ovsdb_idl_txn_set_dry_run(txn);
1126     }
1127
1128     ovsdb_idl_txn_add_comment(txn, "ovs-nbctl: %s", args);
1129
1130     symtab = ovsdb_symbol_table_create();
1131     for (c = commands; c < &commands[n_commands]; c++) {
1132         ds_init(&c->output);
1133         c->table = NULL;
1134     }
1135     ctl_context_init(&ctx, NULL, idl, txn, symtab, NULL);
1136     for (c = commands; c < &commands[n_commands]; c++) {
1137         ctl_context_init_command(&ctx, c);
1138         if (c->syntax->run) {
1139             (c->syntax->run)(&ctx);
1140         }
1141         ctl_context_done_command(&ctx, c);
1142
1143         if (ctx.try_again) {
1144             ctl_context_done(&ctx, NULL);
1145             goto try_again;
1146         }
1147     }
1148     ctl_context_done(&ctx, NULL);
1149
1150     SHASH_FOR_EACH (node, &symtab->sh) {
1151         struct ovsdb_symbol *symbol = node->data;
1152         if (!symbol->created) {
1153             ctl_fatal("row id \"%s\" is referenced but never created (e.g. "
1154                       "with \"-- --id=%s create ...\")",
1155                       node->name, node->name);
1156         }
1157         if (!symbol->strong_ref) {
1158             if (!symbol->weak_ref) {
1159                 VLOG_WARN("row id \"%s\" was created but no reference to it "
1160                           "was inserted, so it will not actually appear in "
1161                           "the database", node->name);
1162             } else {
1163                 VLOG_WARN("row id \"%s\" was created but only a weak "
1164                           "reference to it was inserted, so it will not "
1165                           "actually appear in the database", node->name);
1166             }
1167         }
1168     }
1169
1170     status = ovsdb_idl_txn_commit_block(txn);
1171     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
1172         for (c = commands; c < &commands[n_commands]; c++) {
1173             if (c->syntax->postprocess) {
1174                 ctl_context_init(&ctx, c, idl, txn, symtab, NULL);
1175                 (c->syntax->postprocess)(&ctx);
1176                 ctl_context_done(&ctx, c);
1177             }
1178         }
1179     }
1180     error = xstrdup(ovsdb_idl_txn_get_error(txn));
1181
1182     switch (status) {
1183     case TXN_UNCOMMITTED:
1184     case TXN_INCOMPLETE:
1185         OVS_NOT_REACHED();
1186
1187     case TXN_ABORTED:
1188         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
1189         ctl_fatal("transaction aborted");
1190
1191     case TXN_UNCHANGED:
1192     case TXN_SUCCESS:
1193         break;
1194
1195     case TXN_TRY_AGAIN:
1196         goto try_again;
1197
1198     case TXN_ERROR:
1199         ctl_fatal("transaction error: %s", error);
1200
1201     case TXN_NOT_LOCKED:
1202         /* Should not happen--we never call ovsdb_idl_set_lock(). */
1203         ctl_fatal("database not locked");
1204
1205     default:
1206         OVS_NOT_REACHED();
1207     }
1208     free(error);
1209
1210     ovsdb_symbol_table_destroy(symtab);
1211
1212     for (c = commands; c < &commands[n_commands]; c++) {
1213         struct ds *ds = &c->output;
1214
1215         if (c->table) {
1216             table_print(c->table, &table_style);
1217         } else if (oneline) {
1218             size_t j;
1219
1220             ds_chomp(ds, '\n');
1221             for (j = 0; j < ds->length; j++) {
1222                 int ch = ds->string[j];
1223                 switch (ch) {
1224                 case '\n':
1225                     fputs("\\n", stdout);
1226                     break;
1227
1228                 case '\\':
1229                     fputs("\\\\", stdout);
1230                     break;
1231
1232                 default:
1233                     putchar(ch);
1234                 }
1235             }
1236             putchar('\n');
1237         } else {
1238             fputs(ds_cstr(ds), stdout);
1239         }
1240         ds_destroy(&c->output);
1241         table_destroy(c->table);
1242         free(c->table);
1243
1244         shash_destroy_free_data(&c->options);
1245     }
1246     free(commands);
1247     ovsdb_idl_txn_destroy(txn);
1248     ovsdb_idl_destroy(idl);
1249
1250     exit(EXIT_SUCCESS);
1251
1252 try_again:
1253     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
1254      * resources and return so that the caller can try again. */
1255     if (txn) {
1256         ovsdb_idl_txn_abort(txn);
1257         ovsdb_idl_txn_destroy(txn);
1258         the_idl_txn = NULL;
1259     }
1260     ovsdb_symbol_table_destroy(symtab);
1261     for (c = commands; c < &commands[n_commands]; c++) {
1262         ds_destroy(&c->output);
1263         table_destroy(c->table);
1264         free(c->table);
1265     }
1266     free(error);
1267 }
1268
1269 /* Frees the current transaction and the underlying IDL and then calls
1270  * exit(status).
1271  *
1272  * Freeing the transaction and the IDL is not strictly necessary, but it makes
1273  * for a clean memory leak report from valgrind in the normal case.  That makes
1274  * it easier to notice real memory leaks. */
1275 static void
1276 nbctl_exit(int status)
1277 {
1278     if (the_idl_txn) {
1279         ovsdb_idl_txn_abort(the_idl_txn);
1280         ovsdb_idl_txn_destroy(the_idl_txn);
1281     }
1282     ovsdb_idl_destroy(the_idl);
1283     exit(status);
1284 }
1285
1286 static const struct ctl_command_syntax nbctl_commands[] = {
1287     { "show", 0, 1, "[LSWITCH]", NULL, nbctl_show, NULL, "", RO },
1288
1289     /* lswitch commands. */
1290     { "lswitch-add", 0, 1, "[LSWITCH]", NULL, nbctl_lswitch_add,
1291       NULL, "", RW },
1292     { "lswitch-del", 1, 1, "LSWITCH", NULL, nbctl_lswitch_del,
1293       NULL, "", RW },
1294     { "lswitch-list", 0, 0, "", NULL, nbctl_lswitch_list, NULL, "", RO },
1295
1296     /* acl commands. */
1297     { "acl-add", 5, 5, "LSWITCH DIRECTION PRIORITY MATCH ACTION", NULL,
1298       nbctl_acl_add, NULL, "--log", RW },
1299     { "acl-del", 1, 4, "LSWITCH [DIRECTION [PRIORITY MATCH]]", NULL,
1300       nbctl_acl_del, NULL, "", RW },
1301     { "acl-list", 1, 1, "LSWITCH", NULL, nbctl_acl_list, NULL, "", RO },
1302
1303     /* lport commands. */
1304     { "lport-add", 2, 4, "LSWITCH LPORT [PARENT] [TAG]", NULL, nbctl_lport_add,
1305       NULL, "", RW },
1306     { "lport-del", 1, 1, "LPORT", NULL, nbctl_lport_del, NULL, "", RO },
1307     { "lport-list", 1, 1, "LSWITCH", NULL, nbctl_lport_list, NULL, "", RO },
1308     { "lport-get-parent", 1, 1, "LPORT", NULL, nbctl_lport_get_parent, NULL,
1309       "", RO },
1310     { "lport-get-tag", 1, 1, "LPORT", NULL, nbctl_lport_get_tag, NULL, "",
1311       RO },
1312     { "lport-set-addresses", 1, INT_MAX, "LPORT [ADDRESS]...", NULL,
1313       nbctl_lport_set_addresses, NULL, "", RW },
1314     { "lport-get-addresses", 1, 1, "LPORT", NULL,
1315       nbctl_lport_get_addresses, NULL,
1316       "", RO },
1317     { "lport-set-port-security", 0, INT_MAX, "LPORT [ADDRS]...", NULL,
1318       nbctl_lport_set_port_security, NULL, "", RW },
1319     { "lport-get-port-security", 1, 1, "LPORT", NULL,
1320       nbctl_lport_get_port_security, NULL, "", RO },
1321     { "lport-get-up", 1, 1, "LPORT", NULL, nbctl_lport_get_up, NULL, "", RO },
1322     { "lport-set-enabled", 2, 2, "LPORT STATE", NULL, nbctl_lport_set_enabled,
1323       NULL, "", RW },
1324     { "lport-get-enabled", 1, 1, "LPORT", NULL, nbctl_lport_get_enabled, NULL,
1325       "", RO },
1326     { "lport-set-type", 2, 2, "LPORT TYPE", NULL, nbctl_lport_set_type, NULL,
1327       "", RW },
1328     { "lport-get-type", 1, 1, "LPORT", NULL, nbctl_lport_get_type, NULL, "",
1329       RO },
1330     { "lport-set-options", 1, INT_MAX, "LPORT KEY=VALUE [KEY=VALUE]...", NULL,
1331       nbctl_lport_set_options, NULL, "", RW },
1332     { "lport-get-options", 1, 1, "LPORT", NULL, nbctl_lport_get_options, NULL,
1333       "", RO },
1334
1335     {NULL, 0, 0, NULL, NULL, NULL, NULL, "", RO},
1336 };
1337
1338 /* Registers nbctl and common db commands. */
1339 static void
1340 nbctl_cmd_init(void)
1341 {
1342     ctl_init(tables, NULL, nbctl_exit);
1343     ctl_register_commands(nbctl_commands);
1344 }