ovn: Support multiple addresses on a single logical router port.
[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 "packets.h"
29 #include "poll-loop.h"
30 #include "process.h"
31 #include "smap.h"
32 #include "sset.h"
33 #include "stream.h"
34 #include "stream-ssl.h"
35 #include "svec.h"
36 #include "table.h"
37 #include "timeval.h"
38 #include "util.h"
39 #include "openvswitch/vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(nbctl);
42
43 /* --db: The database server to contact. */
44 static const char *db;
45
46 /* --oneline: Write each command's output as a single line? */
47 static bool oneline;
48
49 /* --dry-run: Do not commit any changes. */
50 static bool dry_run;
51
52 /* --timeout: Time to wait for a connection to 'db'. */
53 static int timeout;
54
55 /* Format for table output. */
56 static struct table_style table_style = TABLE_STYLE_DEFAULT;
57
58 /* The IDL we're using and the current transaction, if any.
59  * This is for use by nbctl_exit() only, to allow it to clean up.
60  * Other code should use its context arguments. */
61 static struct ovsdb_idl *the_idl;
62 static struct ovsdb_idl_txn *the_idl_txn;
63 OVS_NO_RETURN static void nbctl_exit(int status);
64
65 static void nbctl_cmd_init(void);
66 OVS_NO_RETURN static void usage(void);
67 static void parse_options(int argc, char *argv[], struct shash *local_options);
68 static const char *nbctl_default_db(void);
69 static void run_prerequisites(struct ctl_command[], size_t n_commands,
70                               struct ovsdb_idl *);
71 static bool do_nbctl(const char *args, struct ctl_command *, size_t n,
72                      struct ovsdb_idl *);
73
74 int
75 main(int argc, char *argv[])
76 {
77     struct ovsdb_idl *idl;
78     struct ctl_command *commands;
79     struct shash local_options;
80     unsigned int seqno;
81     size_t n_commands;
82     char *args;
83
84     set_program_name(argv[0]);
85     fatal_ignore_sigpipe();
86     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
87     vlog_set_levels_from_string_assert("reconnect:warn");
88     nbrec_init();
89
90     nbctl_cmd_init();
91
92     /* Log our arguments.  This is often valuable for debugging systems. */
93     args = process_escape_args(argv);
94     VLOG(ctl_might_write_to_db(argv) ? VLL_INFO : VLL_DBG,
95          "Called as %s", args);
96
97     /* Parse command line. */
98     shash_init(&local_options);
99     parse_options(argc, argv, &local_options);
100     commands = ctl_parse_commands(argc - optind, argv + optind, &local_options,
101                                   &n_commands);
102
103     if (timeout) {
104         time_alarm(timeout);
105     }
106
107     /* Initialize IDL. */
108     idl = the_idl = ovsdb_idl_create(db, &nbrec_idl_class, true, false);
109     run_prerequisites(commands, n_commands, idl);
110
111     /* Execute the commands.
112      *
113      * 'seqno' is the database sequence number for which we last tried to
114      * execute our transaction.  There's no point in trying to commit more than
115      * once for any given sequence number, because if the transaction fails
116      * it's because the database changed and we need to obtain an up-to-date
117      * view of the database before we try the transaction again. */
118     seqno = ovsdb_idl_get_seqno(idl);
119     for (;;) {
120         ovsdb_idl_run(idl);
121         if (!ovsdb_idl_is_alive(idl)) {
122             int retval = ovsdb_idl_get_last_error(idl);
123             ctl_fatal("%s: database connection failed (%s)",
124                         db, ovs_retval_to_string(retval));
125         }
126
127         if (seqno != ovsdb_idl_get_seqno(idl)) {
128             seqno = ovsdb_idl_get_seqno(idl);
129             if (do_nbctl(args, commands, n_commands, idl)) {
130                 free(args);
131                 exit(EXIT_SUCCESS);
132             }
133         }
134
135         if (seqno == ovsdb_idl_get_seqno(idl)) {
136             ovsdb_idl_wait(idl);
137             poll_block();
138         }
139     }
140 }
141
142 static const char *
143 nbctl_default_db(void)
144 {
145     static char *def;
146     if (!def) {
147         def = getenv("OVN_NB_DB");
148         if (!def) {
149             def = xasprintf("unix:%s/ovnnb_db.sock", ovs_rundir());
150         }
151     }
152     return def;
153 }
154
155 static void
156 parse_options(int argc, char *argv[], struct shash *local_options)
157 {
158     enum {
159         OPT_DB = UCHAR_MAX + 1,
160         OPT_NO_SYSLOG,
161         OPT_DRY_RUN,
162         OPT_ONELINE,
163         OPT_LOCAL,
164         OPT_COMMANDS,
165         OPT_OPTIONS,
166         VLOG_OPTION_ENUMS,
167         TABLE_OPTION_ENUMS
168     };
169     static const struct option global_long_options[] = {
170         {"db", required_argument, NULL, OPT_DB},
171         {"no-syslog", no_argument, NULL, OPT_NO_SYSLOG},
172         {"dry-run", no_argument, NULL, OPT_DRY_RUN},
173         {"oneline", no_argument, NULL, OPT_ONELINE},
174         {"timeout", required_argument, NULL, 't'},
175         {"help", no_argument, NULL, 'h'},
176         {"commands", no_argument, NULL, OPT_COMMANDS},
177         {"options", no_argument, NULL, OPT_OPTIONS},
178         {"version", no_argument, NULL, 'V'},
179         VLOG_LONG_OPTIONS,
180         STREAM_SSL_LONG_OPTIONS,
181         TABLE_LONG_OPTIONS,
182         {NULL, 0, NULL, 0},
183     };
184     const int n_global_long_options = ARRAY_SIZE(global_long_options) - 1;
185     char *tmp, *short_options;
186
187     struct option *options;
188     size_t allocated_options;
189     size_t n_options;
190     size_t i;
191
192     tmp = ovs_cmdl_long_options_to_short_options(global_long_options);
193     short_options = xasprintf("+%s", tmp);
194     free(tmp);
195
196     /* We want to parse both global and command-specific options here, but
197      * getopt_long() isn't too convenient for the job.  We copy our global
198      * options into a dynamic array, then append all of the command-specific
199      * options. */
200     options = xmemdup(global_long_options, sizeof global_long_options);
201     allocated_options = ARRAY_SIZE(global_long_options);
202     n_options = n_global_long_options;
203     ctl_add_cmd_options(&options, &n_options, &allocated_options, OPT_LOCAL);
204     table_style.format = TF_LIST;
205
206     for (;;) {
207         int idx;
208         int c;
209
210         c = getopt_long(argc, argv, short_options, options, &idx);
211         if (c == -1) {
212             break;
213         }
214
215         switch (c) {
216         case OPT_DB:
217             db = optarg;
218             break;
219
220         case OPT_ONELINE:
221             oneline = true;
222             break;
223
224         case OPT_NO_SYSLOG:
225             vlog_set_levels(&this_module, VLF_SYSLOG, VLL_WARN);
226             break;
227
228         case OPT_DRY_RUN:
229             dry_run = true;
230             break;
231
232         case OPT_LOCAL:
233             if (shash_find(local_options, options[idx].name)) {
234                 ctl_fatal("'%s' option specified multiple times",
235                             options[idx].name);
236             }
237             shash_add_nocopy(local_options,
238                              xasprintf("--%s", options[idx].name),
239                              nullable_xstrdup(optarg));
240             break;
241
242         case 'h':
243             usage();
244             exit(EXIT_SUCCESS);
245
246         case OPT_COMMANDS:
247             ctl_print_commands();
248
249         case OPT_OPTIONS:
250             ctl_print_options(global_long_options);
251
252         case 'V':
253             ovs_print_version(0, 0);
254             printf("DB Schema %s\n", nbrec_get_db_version());
255             exit(EXIT_SUCCESS);
256
257         case 't':
258             timeout = strtoul(optarg, NULL, 10);
259             if (timeout < 0) {
260                 ctl_fatal("value %s on -t or --timeout is invalid", optarg);
261             }
262             break;
263
264         VLOG_OPTION_HANDLERS
265         TABLE_OPTION_HANDLERS(&table_style)
266         STREAM_SSL_OPTION_HANDLERS
267
268         case '?':
269             exit(EXIT_FAILURE);
270
271         default:
272             abort();
273         }
274     }
275     free(short_options);
276
277     if (!db) {
278         db = nbctl_default_db();
279     }
280
281     for (i = n_global_long_options; options[i].name; i++) {
282         free(CONST_CAST(char *, options[i].name));
283     }
284     free(options);
285 }
286
287 static void
288 usage(void)
289 {
290     printf("\
291 %s: OVN northbound DB management utility\n\
292 usage: %s [OPTIONS] COMMAND [ARG...]\n\
293 \n\
294 General commands:\n\
295   show                      print overview of database contents\n\
296   show SWITCH               print overview of database contents for SWITCH\n\
297   show ROUTER               print overview of database contents for ROUTER\n\
298 \n\
299 Logical switch commands:\n\
300   ls-add [SWITCH]           create a logical switch named SWITCH\n\
301   ls-del SWITCH             delete SWITCH and all its ports\n\
302   ls-list                   print the names of all logical switches\n\
303 \n\
304 ACL commands:\n\
305   acl-add SWITCH DIRECTION PRIORITY MATCH ACTION [log]\n\
306                             add an ACL to SWITCH\n\
307   acl-del SWITCH [DIRECTION [PRIORITY MATCH]]\n\
308                             remove ACLs from SWITCH\n\
309   acl-list SWITCH           print ACLs for SWITCH\n\
310 \n\
311 Logical switch port commands:\n\
312   lsp-add SWITCH PORT       add logical port PORT on SWITCH\n\
313   lsp-add SWITCH PORT PARENT TAG\n\
314                             add logical port PORT on SWITCH with PARENT\n\
315                             on TAG\n\
316   lsp-del PORT              delete PORT from its attached switch\n\
317   lsp-list SWITCH           print the names of all logical ports on SWITCH\n\
318   lsp-get-parent PORT       get the parent of PORT if set\n\
319   lsp-get-tag PORT          get the PORT's tag if set\n\
320   lsp-set-addresses PORT [ADDRESS]...\n\
321                             set MAC or MAC+IP addresses for PORT.\n\
322   lsp-get-addresses PORT    get a list of MAC addresses on PORT\n\
323   lsp-set-port-security PORT [ADDRS]...\n\
324                             set port security addresses for PORT.\n\
325   lsp-get-port-security PORT    get PORT's port security addresses\n\
326   lsp-get-up PORT           get state of PORT ('up' or 'down')\n\
327   lsp-set-enabled PORT STATE\n\
328                             set administrative state PORT\n\
329                             ('enabled' or 'disabled')\n\
330   lsp-get-enabled PORT      get administrative state PORT\n\
331                             ('enabled' or 'disabled')\n\
332   lsp-set-type PORT TYPE    set the type for PORT\n\
333   lsp-get-type PORT         get the type for PORT\n\
334   lsp-set-options PORT KEY=VALUE [KEY=VALUE]...\n\
335                             set options related to the type of PORT\n\
336   lsp-get-options PORT      get the type specific options for PORT\n\
337 \n\
338 Logical router commands:\n\
339   lr-add [ROUTER]           create a logical router named ROUTER\n\
340   lr-del ROUTER             delete ROUTER and all its ports\n\
341   lr-list                   print the names of all logical routers\n\
342 \n\
343 Logical router port commands:\n\
344   lrp-add ROUTER PORT MAC NETWORK... [peer=PEER]\n\
345                             add logical port PORT on ROUTER\n\
346   lrp-del PORT              delete PORT from its attached router\n\
347   lrp-list ROUTER           print the names of all ports on ROUTER\n\
348   lrp-set-enabled PORT STATE\n\
349                             set administrative state PORT\n\
350                             ('enabled' or 'disabled')\n\
351   lrp-get-enabled PORT      get administrative state PORT\n\
352                             ('enabled' or 'disabled')\n\
353 \n\
354 Route commands:\n\
355   lr-route-add ROUTER PREFIX NEXTHOP [PORT]\n\
356                             add a route to ROUTER\n\
357   lr-route-del ROUTER [PREFIX]\n\
358                             remove routes from ROUTER\n\
359   lr-route-list ROUTER      print routes for ROUTER\n\
360 \n\
361 %s\
362 \n\
363 Options:\n\
364   --db=DATABASE               connect to DATABASE\n\
365                               (default: %s)\n\
366   -t, --timeout=SECS          wait at most SECS seconds\n\
367   --dry-run                   do not commit changes to database\n\
368   --oneline                   print exactly one line of output per command\n",
369            program_name, program_name, ctl_get_db_cmd_usage(), nbctl_default_db());
370     vlog_usage();
371     printf("\
372   --no-syslog             equivalent to --verbose=nbctl:syslog:warn\n");
373     printf("\n\
374 Other options:\n\
375   -h, --help                  display this help message\n\
376   -V, --version               display version information\n");
377     exit(EXIT_SUCCESS);
378 }
379 \f
380
381 /* Find a logical router given its id. */
382 static const struct nbrec_logical_router *
383 lr_by_name_or_uuid(struct ctl_context *ctx, const char *id,
384                         bool must_exist)
385 {
386     const struct nbrec_logical_router *lr = NULL;
387     bool is_uuid = false;
388     struct uuid lr_uuid;
389
390     if (uuid_from_string(&lr_uuid, id)) {
391         is_uuid = true;
392         lr = nbrec_logical_router_get_for_uuid(ctx->idl, &lr_uuid);
393     }
394
395     if (!lr) {
396         const struct nbrec_logical_router *iter;
397
398         NBREC_LOGICAL_ROUTER_FOR_EACH(iter, ctx->idl) {
399             if (strcmp(iter->name, id)) {
400                 continue;
401             }
402             if (lr) {
403                 ctl_fatal("Multiple logical routers named '%s'.  "
404                           "Use a UUID.", id);
405             }
406             lr = iter;
407         }
408     }
409
410     if (!lr && must_exist) {
411         ctl_fatal("%s: router %s not found", id, is_uuid ? "UUID" : "name");
412     }
413
414     return lr;
415 }
416
417 static const struct nbrec_logical_switch *
418 ls_by_name_or_uuid(struct ctl_context *ctx, const char *id, bool must_exist)
419 {
420     const struct nbrec_logical_switch *ls = NULL;
421
422     struct uuid ls_uuid;
423     bool is_uuid = uuid_from_string(&ls_uuid, id);
424     if (is_uuid) {
425         ls = nbrec_logical_switch_get_for_uuid(ctx->idl, &ls_uuid);
426     }
427
428     if (!ls) {
429         const struct nbrec_logical_switch *iter;
430
431         NBREC_LOGICAL_SWITCH_FOR_EACH(iter, ctx->idl) {
432             if (strcmp(iter->name, id)) {
433                 continue;
434             }
435             if (ls) {
436                 ctl_fatal("Multiple logical switches named '%s'.  "
437                           "Use a UUID.", id);
438             }
439             ls = iter;
440         }
441     }
442
443     if (!ls && must_exist) {
444         ctl_fatal("%s: switch %s not found", id, is_uuid ? "UUID" : "name");
445     }
446
447     return ls;
448 }
449
450 /* Given pointer to logical router, this routine prints the router
451  * information.  */
452 static void
453 print_lr(const struct nbrec_logical_router *lr, struct ds *s)
454 {
455     ds_put_format(s, "    router "UUID_FMT" (%s)\n",
456                   UUID_ARGS(&lr->header_.uuid), lr->name);
457
458     for (size_t i = 0; i < lr->n_ports; i++) {
459         const struct nbrec_logical_router_port *lrp = lr->ports[i];
460         ds_put_format(s, "        port %s\n", lrp->name);
461         if (lrp->mac) {
462             ds_put_cstr(s, "            mac: ");
463             ds_put_format(s, "\"%s\"", lrp->mac);
464         }
465         ds_put_format(s, "\n");
466     }
467 }
468
469 static void
470 print_ls(const struct nbrec_logical_switch *ls, struct ds *s)
471 {
472     ds_put_format(s, "    switch "UUID_FMT" (%s)\n",
473                   UUID_ARGS(&ls->header_.uuid), ls->name);
474
475     for (size_t i = 0; i < ls->n_ports; i++) {
476         const struct nbrec_logical_switch_port *lsp = ls->ports[i];
477
478         ds_put_format(s, "        port %s\n", lsp->name);
479         if (lsp->parent_name) {
480             ds_put_format(s, "            parent: %s\n", lsp->parent_name);
481         }
482         if (lsp->n_tag) {
483             ds_put_format(s, "            tag: %"PRIu64"\n", lsp->tag[0]);
484         }
485         if (lsp->n_addresses) {
486             ds_put_cstr(s, "            addresses: [");
487             for (size_t j = 0; j < lsp->n_addresses; j++) {
488                 ds_put_format(s, "%s\"%s\"",
489                         j == 0 ? "" : ", ",
490                         lsp->addresses[j]);
491             }
492             ds_put_cstr(s, "]\n");
493         }
494     }
495 }
496
497 static void
498 nbctl_show(struct ctl_context *ctx)
499 {
500     const struct nbrec_logical_switch *ls;
501
502     if (ctx->argc == 2) {
503         ls = ls_by_name_or_uuid(ctx, ctx->argv[1], false);
504         if (ls) {
505             print_ls(ls, &ctx->output);
506         }
507     } else {
508         NBREC_LOGICAL_SWITCH_FOR_EACH(ls, ctx->idl) {
509             print_ls(ls, &ctx->output);
510         }
511     }
512     const struct nbrec_logical_router *lr;
513
514     if (ctx->argc == 2) {
515         lr = lr_by_name_or_uuid(ctx, ctx->argv[1], false);
516         if (lr) {
517             print_lr(lr, &ctx->output);
518         }
519     } else {
520         NBREC_LOGICAL_ROUTER_FOR_EACH(lr, ctx->idl) {
521             print_lr(lr, &ctx->output);
522         }
523     }
524 }
525
526 static void
527 nbctl_ls_add(struct ctl_context *ctx)
528 {
529     const char *ls_name = ctx->argc == 2 ? ctx->argv[1] : NULL;
530
531     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
532     bool add_duplicate = shash_find(&ctx->options, "--add-duplicate") != NULL;
533     if (may_exist && add_duplicate) {
534         ctl_fatal("--may-exist and --add-duplicate may not be used together");
535     }
536
537     if (ls_name) {
538         if (!add_duplicate) {
539             const struct nbrec_logical_switch *ls;
540             NBREC_LOGICAL_SWITCH_FOR_EACH (ls, ctx->idl) {
541                 if (!strcmp(ls->name, ls_name)) {
542                     if (may_exist) {
543                         return;
544                     }
545                     ctl_fatal("%s: a switch with this name already exists",
546                               ls_name);
547                 }
548             }
549         }
550     } else if (may_exist) {
551         ctl_fatal("--may-exist requires specifying a name");
552     } else if (add_duplicate) {
553         ctl_fatal("--add-duplicate requires specifying a name");
554     }
555
556     struct nbrec_logical_switch *ls;
557     ls = nbrec_logical_switch_insert(ctx->txn);
558     if (ls_name) {
559         nbrec_logical_switch_set_name(ls, ls_name);
560     }
561 }
562
563 static void
564 nbctl_ls_del(struct ctl_context *ctx)
565 {
566     bool must_exist = !shash_find(&ctx->options, "--if-exists");
567     const char *id = ctx->argv[1];
568     const struct nbrec_logical_switch *ls;
569
570     ls = ls_by_name_or_uuid(ctx, id, must_exist);
571     if (!ls) {
572         return;
573     }
574
575     nbrec_logical_switch_delete(ls);
576 }
577
578 static void
579 nbctl_ls_list(struct ctl_context *ctx)
580 {
581     const struct nbrec_logical_switch *ls;
582     struct smap lswitches;
583
584     smap_init(&lswitches);
585     NBREC_LOGICAL_SWITCH_FOR_EACH(ls, ctx->idl) {
586         smap_add_format(&lswitches, ls->name, UUID_FMT " (%s)",
587                         UUID_ARGS(&ls->header_.uuid), ls->name);
588     }
589     const struct smap_node **nodes = smap_sort(&lswitches);
590     for (size_t i = 0; i < smap_count(&lswitches); i++) {
591         const struct smap_node *node = nodes[i];
592         ds_put_format(&ctx->output, "%s\n", node->value);
593     }
594     smap_destroy(&lswitches);
595     free(nodes);
596 }
597 \f
598 static const struct nbrec_logical_switch_port *
599 lsp_by_name_or_uuid(struct ctl_context *ctx, const char *id,
600                     bool must_exist)
601 {
602     const struct nbrec_logical_switch_port *lsp = NULL;
603
604     struct uuid lsp_uuid;
605     bool is_uuid = uuid_from_string(&lsp_uuid, id);
606     if (is_uuid) {
607         lsp = nbrec_logical_switch_port_get_for_uuid(ctx->idl, &lsp_uuid);
608     }
609
610     if (!lsp) {
611         NBREC_LOGICAL_SWITCH_PORT_FOR_EACH(lsp, ctx->idl) {
612             if (!strcmp(lsp->name, id)) {
613                 break;
614             }
615         }
616     }
617
618     if (!lsp && must_exist) {
619         ctl_fatal("%s: port %s not found", id, is_uuid ? "UUID" : "name");
620     }
621
622     return lsp;
623 }
624
625 /* Returns the logical switch that contains 'lsp'. */
626 static const struct nbrec_logical_switch *
627 lsp_to_ls(const struct ovsdb_idl *idl,
628                const struct nbrec_logical_switch_port *lsp)
629 {
630     const struct nbrec_logical_switch *ls;
631     NBREC_LOGICAL_SWITCH_FOR_EACH (ls, idl) {
632         for (size_t i = 0; i < ls->n_ports; i++) {
633             if (ls->ports[i] == lsp) {
634                 return ls;
635             }
636         }
637     }
638
639     /* Can't happen because of the database schema */
640     ctl_fatal("logical port %s is not part of any logical switch",
641               lsp->name);
642 }
643
644 static const char *
645 ls_get_name(const struct nbrec_logical_switch *ls,
646                  char uuid_s[UUID_LEN + 1], size_t uuid_s_size)
647 {
648     if (ls->name[0]) {
649         return ls->name;
650     }
651     snprintf(uuid_s, uuid_s_size, UUID_FMT, UUID_ARGS(&ls->header_.uuid));
652     return uuid_s;
653 }
654
655 static void
656 nbctl_lsp_add(struct ctl_context *ctx)
657 {
658     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
659
660     const struct nbrec_logical_switch *ls;
661     ls = ls_by_name_or_uuid(ctx, ctx->argv[1], true);
662
663     const char *parent_name;
664     int64_t tag;
665     if (ctx->argc == 3) {
666         parent_name = NULL;
667         tag = -1;
668     } else if (ctx->argc == 5) {
669         /* Validate tag. */
670         parent_name = ctx->argv[3];
671         if (!ovs_scan(ctx->argv[4], "%"SCNd64, &tag)
672             || tag < 0 || tag > 4095) {
673             ctl_fatal("%s: invalid tag", ctx->argv[4]);
674         }
675     } else {
676         ctl_fatal("lsp-add with parent must also specify a tag");
677     }
678
679     const char *lsp_name = ctx->argv[2];
680     const struct nbrec_logical_switch_port *lsp;
681     lsp = lsp_by_name_or_uuid(ctx, lsp_name, false);
682     if (lsp) {
683         if (!may_exist) {
684             ctl_fatal("%s: a port with this name already exists",
685                       lsp_name);
686         }
687
688         const struct nbrec_logical_switch *lsw;
689         lsw = lsp_to_ls(ctx->idl, lsp);
690         if (lsw != ls) {
691             char uuid_s[UUID_LEN + 1];
692             ctl_fatal("%s: port already exists but in switch %s", lsp_name,
693                       ls_get_name(lsw, uuid_s, sizeof uuid_s));
694         }
695
696         if (parent_name) {
697             if (!lsp->parent_name) {
698                 ctl_fatal("%s: port already exists but has no parent",
699                           lsp_name);
700             } else if (strcmp(parent_name, lsp->parent_name)) {
701                 ctl_fatal("%s: port already exists with different parent %s",
702                           lsp_name, lsp->parent_name);
703             }
704
705             if (!lsp->n_tag) {
706                 ctl_fatal("%s: port already exists but has no tag",
707                           lsp_name);
708             } else if (lsp->tag[0] != tag) {
709                 ctl_fatal("%s: port already exists with different "
710                           "tag %"PRId64, lsp_name, lsp->tag[0]);
711             }
712         } else {
713             if (lsp->parent_name) {
714                 ctl_fatal("%s: port already exists but has parent %s",
715                           lsp_name, lsp->parent_name);
716             }
717         }
718
719         return;
720     }
721
722     /* Create the logical port. */
723     lsp = nbrec_logical_switch_port_insert(ctx->txn);
724     nbrec_logical_switch_port_set_name(lsp, lsp_name);
725     if (tag >= 0) {
726         nbrec_logical_switch_port_set_parent_name(lsp, parent_name);
727         nbrec_logical_switch_port_set_tag(lsp, &tag, 1);
728     }
729
730     /* Insert the logical port into the logical switch. */
731     nbrec_logical_switch_verify_ports(ls);
732     struct nbrec_logical_switch_port **new_ports = xmalloc(sizeof *new_ports *
733                                                     (ls->n_ports + 1));
734     memcpy(new_ports, ls->ports, sizeof *new_ports * ls->n_ports);
735     new_ports[ls->n_ports] = CONST_CAST(struct nbrec_logical_switch_port *,
736                                              lsp);
737     nbrec_logical_switch_set_ports(ls, new_ports, ls->n_ports + 1);
738     free(new_ports);
739 }
740
741 /* Removes logical switch port 'ls->ports[idx]'. */
742 static void
743 remove_lsp(const struct nbrec_logical_switch *ls, size_t idx)
744 {
745     const struct nbrec_logical_switch_port *lsp = ls->ports[idx];
746
747     /* First remove 'lsp' from the array of ports.  This is what will
748      * actually cause the logical port to be deleted when the transaction is
749      * sent to the database server (due to garbage collection). */
750     struct nbrec_logical_switch_port **new_ports
751         = xmemdup(ls->ports, sizeof *new_ports * ls->n_ports);
752     new_ports[idx] = new_ports[ls->n_ports - 1];
753     nbrec_logical_switch_verify_ports(ls);
754     nbrec_logical_switch_set_ports(ls, new_ports, ls->n_ports - 1);
755     free(new_ports);
756
757     /* Delete 'lsp' from the IDL.  This won't have a real effect on the
758      * database server (the IDL will suppress it in fact) but it means that it
759      * won't show up when we iterate with NBREC_LOGICAL_SWITCH_PORT_FOR_EACH
760      * later. */
761     nbrec_logical_switch_port_delete(lsp);
762 }
763
764 static void
765 nbctl_lsp_del(struct ctl_context *ctx)
766 {
767     bool must_exist = !shash_find(&ctx->options, "--if-exists");
768     const struct nbrec_logical_switch_port *lsp;
769
770     lsp = lsp_by_name_or_uuid(ctx, ctx->argv[1], must_exist);
771     if (!lsp) {
772         return;
773     }
774
775     /* Find the switch that contains 'lsp', then delete it. */
776     const struct nbrec_logical_switch *ls;
777     NBREC_LOGICAL_SWITCH_FOR_EACH (ls, ctx->idl) {
778         for (size_t i = 0; i < ls->n_ports; i++) {
779             if (ls->ports[i] == lsp) {
780                 remove_lsp(ls, i);
781                 return;
782             }
783         }
784     }
785
786     /* Can't happen because of the database schema. */
787     ctl_fatal("logical port %s is not part of any logical switch",
788               ctx->argv[1]);
789 }
790
791 static void
792 nbctl_lsp_list(struct ctl_context *ctx)
793 {
794     const char *id = ctx->argv[1];
795     const struct nbrec_logical_switch *ls;
796     struct smap lsps;
797     size_t i;
798
799     ls = ls_by_name_or_uuid(ctx, id, true);
800
801     smap_init(&lsps);
802     for (i = 0; i < ls->n_ports; i++) {
803         const struct nbrec_logical_switch_port *lsp = ls->ports[i];
804         smap_add_format(&lsps, lsp->name, UUID_FMT " (%s)",
805                         UUID_ARGS(&lsp->header_.uuid), lsp->name);
806     }
807     const struct smap_node **nodes = smap_sort(&lsps);
808     for (i = 0; i < smap_count(&lsps); i++) {
809         const struct smap_node *node = nodes[i];
810         ds_put_format(&ctx->output, "%s\n", node->value);
811     }
812     smap_destroy(&lsps);
813     free(nodes);
814 }
815
816 static void
817 nbctl_lsp_get_parent(struct ctl_context *ctx)
818 {
819     const struct nbrec_logical_switch_port *lsp;
820
821     lsp = lsp_by_name_or_uuid(ctx, ctx->argv[1], true);
822     if (lsp->parent_name) {
823         ds_put_format(&ctx->output, "%s\n", lsp->parent_name);
824     }
825 }
826
827 static void
828 nbctl_lsp_get_tag(struct ctl_context *ctx)
829 {
830     const struct nbrec_logical_switch_port *lsp;
831
832     lsp = lsp_by_name_or_uuid(ctx, ctx->argv[1], true);
833     if (lsp->n_tag > 0) {
834         ds_put_format(&ctx->output, "%"PRId64"\n", lsp->tag[0]);
835     }
836 }
837
838 static void
839 nbctl_lsp_set_addresses(struct ctl_context *ctx)
840 {
841     const char *id = ctx->argv[1];
842     const struct nbrec_logical_switch_port *lsp;
843
844     lsp = lsp_by_name_or_uuid(ctx, id, true);
845
846     int i;
847     for (i = 2; i < ctx->argc; i++) {
848         struct eth_addr ea;
849
850         if (strcmp(ctx->argv[i], "unknown")
851             && !ovs_scan(ctx->argv[i], ETH_ADDR_SCAN_FMT,
852                          ETH_ADDR_SCAN_ARGS(ea))) {
853             ctl_fatal("%s: Invalid address format. See ovn-nb(5). "
854                       "Hint: An Ethernet address must be "
855                       "listed before an IP address, together as a single "
856                       "argument.", ctx->argv[i]);
857         }
858     }
859
860     nbrec_logical_switch_port_set_addresses(lsp,
861             (const char **) ctx->argv + 2, ctx->argc - 2);
862 }
863
864 static void
865 nbctl_lsp_get_addresses(struct ctl_context *ctx)
866 {
867     const char *id = ctx->argv[1];
868     const struct nbrec_logical_switch_port *lsp;
869     struct svec addresses;
870     const char *mac;
871     size_t i;
872
873     lsp = lsp_by_name_or_uuid(ctx, id, true);
874
875     svec_init(&addresses);
876     for (i = 0; i < lsp->n_addresses; i++) {
877         svec_add(&addresses, lsp->addresses[i]);
878     }
879     svec_sort(&addresses);
880     SVEC_FOR_EACH(i, mac, &addresses) {
881         ds_put_format(&ctx->output, "%s\n", mac);
882     }
883     svec_destroy(&addresses);
884 }
885
886 static void
887 nbctl_lsp_set_port_security(struct ctl_context *ctx)
888 {
889     const char *id = ctx->argv[1];
890     const struct nbrec_logical_switch_port *lsp;
891
892     lsp = lsp_by_name_or_uuid(ctx, id, true);
893     nbrec_logical_switch_port_set_port_security(lsp,
894             (const char **) ctx->argv + 2, ctx->argc - 2);
895 }
896
897 static void
898 nbctl_lsp_get_port_security(struct ctl_context *ctx)
899 {
900     const char *id = ctx->argv[1];
901     const struct nbrec_logical_switch_port *lsp;
902     struct svec addrs;
903     const char *addr;
904     size_t i;
905
906     lsp = lsp_by_name_or_uuid(ctx, id, true);
907     svec_init(&addrs);
908     for (i = 0; i < lsp->n_port_security; i++) {
909         svec_add(&addrs, lsp->port_security[i]);
910     }
911     svec_sort(&addrs);
912     SVEC_FOR_EACH(i, addr, &addrs) {
913         ds_put_format(&ctx->output, "%s\n", addr);
914     }
915     svec_destroy(&addrs);
916 }
917
918 static void
919 nbctl_lsp_get_up(struct ctl_context *ctx)
920 {
921     const char *id = ctx->argv[1];
922     const struct nbrec_logical_switch_port *lsp;
923
924     lsp = lsp_by_name_or_uuid(ctx, id, true);
925     ds_put_format(&ctx->output,
926                   "%s\n", (lsp->up && *lsp->up) ? "up" : "down");
927 }
928
929 static bool
930 parse_enabled(const char *state)
931 {
932     if (!strcasecmp(state, "enabled")) {
933         return true;
934     } else if (!strcasecmp(state, "disabled")) {
935         return false;
936     } else {
937         ctl_fatal("%s: state must be \"enabled\" or \"disabled\"", state);
938     }
939 }
940
941 static void
942 nbctl_lsp_set_enabled(struct ctl_context *ctx)
943 {
944     const char *id = ctx->argv[1];
945     const char *state = ctx->argv[2];
946     const struct nbrec_logical_switch_port *lsp;
947
948     lsp = lsp_by_name_or_uuid(ctx, id, true);
949     bool enabled = parse_enabled(state);
950     nbrec_logical_switch_port_set_enabled(lsp, &enabled, 1);
951 }
952
953 static void
954 nbctl_lsp_get_enabled(struct ctl_context *ctx)
955 {
956     const char *id = ctx->argv[1];
957     const struct nbrec_logical_switch_port *lsp;
958
959     lsp = lsp_by_name_or_uuid(ctx, id, true);
960     ds_put_format(&ctx->output, "%s\n",
961                   !lsp->enabled || *lsp->enabled ? "enabled" : "disabled");
962 }
963
964 static void
965 nbctl_lsp_set_type(struct ctl_context *ctx)
966 {
967     const char *id = ctx->argv[1];
968     const char *type = ctx->argv[2];
969     const struct nbrec_logical_switch_port *lsp;
970
971     lsp = lsp_by_name_or_uuid(ctx, id, true);
972     nbrec_logical_switch_port_set_type(lsp, type);
973 }
974
975 static void
976 nbctl_lsp_get_type(struct ctl_context *ctx)
977 {
978     const char *id = ctx->argv[1];
979     const struct nbrec_logical_switch_port *lsp;
980
981     lsp = lsp_by_name_or_uuid(ctx, id, true);
982     ds_put_format(&ctx->output, "%s\n", lsp->type);
983 }
984
985 static void
986 nbctl_lsp_set_options(struct ctl_context *ctx)
987 {
988     const char *id = ctx->argv[1];
989     const struct nbrec_logical_switch_port *lsp;
990     size_t i;
991     struct smap options = SMAP_INITIALIZER(&options);
992
993     lsp = lsp_by_name_or_uuid(ctx, id, true);
994     for (i = 2; i < ctx->argc; i++) {
995         char *key, *value;
996         value = xstrdup(ctx->argv[i]);
997         key = strsep(&value, "=");
998         if (value) {
999             smap_add(&options, key, value);
1000         }
1001         free(key);
1002     }
1003
1004     nbrec_logical_switch_port_set_options(lsp, &options);
1005
1006     smap_destroy(&options);
1007 }
1008
1009 static void
1010 nbctl_lsp_get_options(struct ctl_context *ctx)
1011 {
1012     const char *id = ctx->argv[1];
1013     const struct nbrec_logical_switch_port *lsp;
1014     struct smap_node *node;
1015
1016     lsp = lsp_by_name_or_uuid(ctx, id, true);
1017     SMAP_FOR_EACH(node, &lsp->options) {
1018         ds_put_format(&ctx->output, "%s=%s\n", node->key, node->value);
1019     }
1020 }
1021
1022 enum {
1023     DIR_FROM_LPORT,
1024     DIR_TO_LPORT
1025 };
1026
1027 static int
1028 dir_encode(const char *dir)
1029 {
1030     if (!strcmp(dir, "from-lport")) {
1031         return DIR_FROM_LPORT;
1032     } else if (!strcmp(dir, "to-lport")) {
1033         return DIR_TO_LPORT;
1034     }
1035
1036     OVS_NOT_REACHED();
1037 }
1038
1039 static int
1040 acl_cmp(const void *acl1_, const void *acl2_)
1041 {
1042     const struct nbrec_acl *const *acl1p = acl1_;
1043     const struct nbrec_acl *const *acl2p = acl2_;
1044     const struct nbrec_acl *acl1 = *acl1p;
1045     const struct nbrec_acl *acl2 = *acl2p;
1046
1047     int dir1 = dir_encode(acl1->direction);
1048     int dir2 = dir_encode(acl2->direction);
1049
1050     if (dir1 != dir2) {
1051         return dir1 < dir2 ? -1 : 1;
1052     } else if (acl1->priority != acl2->priority) {
1053         return acl1->priority > acl2->priority ? -1 : 1;
1054     } else {
1055         return strcmp(acl1->match, acl2->match);
1056     }
1057 }
1058
1059 static void
1060 nbctl_acl_list(struct ctl_context *ctx)
1061 {
1062     const struct nbrec_logical_switch *ls;
1063     const struct nbrec_acl **acls;
1064     size_t i;
1065
1066     ls = ls_by_name_or_uuid(ctx, ctx->argv[1], true);
1067
1068     acls = xmalloc(sizeof *acls * ls->n_acls);
1069     for (i = 0; i < ls->n_acls; i++) {
1070         acls[i] = ls->acls[i];
1071     }
1072
1073     qsort(acls, ls->n_acls, sizeof *acls, acl_cmp);
1074
1075     for (i = 0; i < ls->n_acls; i++) {
1076         const struct nbrec_acl *acl = acls[i];
1077         ds_put_format(&ctx->output, "%10s %5"PRId64" (%s) %s%s\n",
1078                       acl->direction, acl->priority,
1079                       acl->match, acl->action, acl->log ? " log" : "");
1080     }
1081
1082     free(acls);
1083 }
1084
1085 static const char *
1086 parse_direction(const char *arg)
1087 {
1088     /* Validate direction.  Only require the first letter. */
1089     if (arg[0] == 't') {
1090         return "to-lport";
1091     } else if (arg[0] == 'f') {
1092         return "from-lport";
1093     } else {
1094         ctl_fatal("%s: direction must be \"to-lport\" or \"from-lport\"", arg);
1095     }
1096 }
1097
1098 static int
1099 parse_priority(const char *arg)
1100 {
1101     /* Validate priority. */
1102     int64_t priority;
1103     if (!ovs_scan(arg, "%"SCNd64, &priority)
1104         || priority < 0 || priority > 32767) {
1105         ctl_fatal("%s: priority must in range 0...32767", arg);
1106     }
1107     return priority;
1108 }
1109
1110 static void
1111 nbctl_acl_add(struct ctl_context *ctx)
1112 {
1113     const struct nbrec_logical_switch *ls;
1114     const char *action = ctx->argv[5];
1115
1116     ls = ls_by_name_or_uuid(ctx, ctx->argv[1], true);
1117
1118     const char *direction = parse_direction(ctx->argv[2]);
1119     int64_t priority = parse_priority(ctx->argv[3]);
1120
1121     /* Validate action. */
1122     if (strcmp(action, "allow") && strcmp(action, "allow-related")
1123         && strcmp(action, "drop") && strcmp(action, "reject")) {
1124         ctl_fatal("%s: action must be one of \"allow\", \"allow-related\", "
1125                   "\"drop\", and \"reject\"", action);
1126         return;
1127     }
1128
1129     /* Create the acl. */
1130     struct nbrec_acl *acl = nbrec_acl_insert(ctx->txn);
1131     nbrec_acl_set_priority(acl, priority);
1132     nbrec_acl_set_direction(acl, direction);
1133     nbrec_acl_set_match(acl, ctx->argv[4]);
1134     nbrec_acl_set_action(acl, action);
1135     if (shash_find(&ctx->options, "--log") != NULL) {
1136         nbrec_acl_set_log(acl, true);
1137     }
1138
1139     /* Insert the acl into the logical switch. */
1140     nbrec_logical_switch_verify_acls(ls);
1141     struct nbrec_acl **new_acls = xmalloc(sizeof *new_acls * (ls->n_acls + 1));
1142     memcpy(new_acls, ls->acls, sizeof *new_acls * ls->n_acls);
1143     new_acls[ls->n_acls] = acl;
1144     nbrec_logical_switch_set_acls(ls, new_acls, ls->n_acls + 1);
1145     free(new_acls);
1146 }
1147
1148 static void
1149 nbctl_acl_del(struct ctl_context *ctx)
1150 {
1151     const struct nbrec_logical_switch *ls;
1152     ls = ls_by_name_or_uuid(ctx, ctx->argv[1], true);
1153
1154     if (ctx->argc != 2 && ctx->argc != 3 && ctx->argc != 5) {
1155         ctl_fatal("cannot specify priority without match");
1156     }
1157
1158     if (ctx->argc == 2) {
1159         /* If direction, priority, and match are not specified, delete
1160          * all ACLs. */
1161         nbrec_logical_switch_verify_acls(ls);
1162         nbrec_logical_switch_set_acls(ls, NULL, 0);
1163         return;
1164     }
1165
1166     const char *direction = parse_direction(ctx->argv[2]);
1167
1168     /* If priority and match are not specified, delete all ACLs with the
1169      * specified direction. */
1170     if (ctx->argc == 3) {
1171         struct nbrec_acl **new_acls = xmalloc(sizeof *new_acls * ls->n_acls);
1172
1173         int n_acls = 0;
1174         for (size_t i = 0; i < ls->n_acls; i++) {
1175             if (strcmp(direction, ls->acls[i]->direction)) {
1176                 new_acls[n_acls++] = ls->acls[i];
1177             }
1178         }
1179
1180         nbrec_logical_switch_verify_acls(ls);
1181         nbrec_logical_switch_set_acls(ls, new_acls, n_acls);
1182         free(new_acls);
1183         return;
1184     }
1185
1186     int64_t priority = parse_priority(ctx->argv[3]);
1187
1188     /* Remove the matching rule. */
1189     for (size_t i = 0; i < ls->n_acls; i++) {
1190         struct nbrec_acl *acl = ls->acls[i];
1191
1192         if (priority == acl->priority && !strcmp(ctx->argv[4], acl->match) &&
1193              !strcmp(direction, acl->direction)) {
1194             struct nbrec_acl **new_acls
1195                 = xmemdup(ls->acls, sizeof *new_acls * ls->n_acls);
1196             new_acls[i] = ls->acls[ls->n_acls - 1];
1197             nbrec_logical_switch_verify_acls(ls);
1198             nbrec_logical_switch_set_acls(ls, new_acls,
1199                                           ls->n_acls - 1);
1200             free(new_acls);
1201             return;
1202         }
1203     }
1204 }
1205 \f
1206 static void
1207 nbctl_lr_add(struct ctl_context *ctx)
1208 {
1209     const char *lr_name = ctx->argc == 2 ? ctx->argv[1] : NULL;
1210
1211     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1212     bool add_duplicate = shash_find(&ctx->options, "--add-duplicate") != NULL;
1213     if (may_exist && add_duplicate) {
1214         ctl_fatal("--may-exist and --add-duplicate may not be used together");
1215     }
1216
1217     if (lr_name) {
1218         if (!add_duplicate) {
1219             const struct nbrec_logical_router *lr;
1220             NBREC_LOGICAL_ROUTER_FOR_EACH (lr, ctx->idl) {
1221                 if (!strcmp(lr->name, lr_name)) {
1222                     if (may_exist) {
1223                         return;
1224                     }
1225                     ctl_fatal("%s: a router with this name already exists",
1226                               lr_name);
1227                 }
1228             }
1229         }
1230     } else if (may_exist) {
1231         ctl_fatal("--may-exist requires specifying a name");
1232     } else if (add_duplicate) {
1233         ctl_fatal("--add-duplicate requires specifying a name");
1234     }
1235
1236     struct nbrec_logical_router *lr;
1237     lr = nbrec_logical_router_insert(ctx->txn);
1238     if (lr_name) {
1239         nbrec_logical_router_set_name(lr, lr_name);
1240     }
1241 }
1242
1243 static void
1244 nbctl_lr_del(struct ctl_context *ctx)
1245 {
1246     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1247     const char *id = ctx->argv[1];
1248     const struct nbrec_logical_router *lr;
1249
1250     lr = lr_by_name_or_uuid(ctx, id, must_exist);
1251     if (!lr) {
1252         return;
1253     }
1254
1255     nbrec_logical_router_delete(lr);
1256 }
1257
1258 static void
1259 nbctl_lr_list(struct ctl_context *ctx)
1260 {
1261     const struct nbrec_logical_router *lr;
1262     struct smap lrs;
1263
1264     smap_init(&lrs);
1265     NBREC_LOGICAL_ROUTER_FOR_EACH(lr, ctx->idl) {
1266         smap_add_format(&lrs, lr->name, UUID_FMT " (%s)",
1267                         UUID_ARGS(&lr->header_.uuid), lr->name);
1268     }
1269     const struct smap_node **nodes = smap_sort(&lrs);
1270     for (size_t i = 0; i < smap_count(&lrs); i++) {
1271         const struct smap_node *node = nodes[i];
1272         ds_put_format(&ctx->output, "%s\n", node->value);
1273     }
1274     smap_destroy(&lrs);
1275     free(nodes);
1276 }
1277
1278 /* The caller must free the returned string. */
1279 static char *
1280 normalize_ipv4_prefix(ovs_be32 ipv4, unsigned int plen)
1281 {
1282     ovs_be32 network = ipv4 & be32_prefix_mask(plen);
1283     if (plen == 32) {
1284         return xasprintf(IP_FMT, IP_ARGS(network));
1285     } else {
1286         return xasprintf(IP_FMT"/%d", IP_ARGS(network), plen);
1287     }
1288 }
1289
1290 /* The caller must free the returned string. */
1291 static char *
1292 normalize_ipv6_prefix(struct in6_addr ipv6, unsigned int plen)
1293 {
1294     char network_s[INET6_ADDRSTRLEN];
1295
1296     struct in6_addr mask = ipv6_create_mask(plen);
1297     struct in6_addr network = ipv6_addr_bitand(&ipv6, &mask);
1298
1299     inet_ntop(AF_INET6, &network, network_s, INET6_ADDRSTRLEN);
1300     if (plen == 128) {
1301         return xasprintf("%s", network_s);
1302     } else {
1303         return xasprintf("%s/%d", network_s, plen);
1304     }
1305 }
1306
1307 /* The caller must free the returned string. */
1308 static char *
1309 normalize_prefix_str(const char *orig_prefix)
1310 {
1311     unsigned int plen;
1312     ovs_be32 ipv4;
1313     char *error;
1314
1315     error = ip_parse_cidr(orig_prefix, &ipv4, &plen);
1316     if (!error) {
1317         return normalize_ipv4_prefix(ipv4, plen);
1318     } else {
1319         struct in6_addr ipv6;
1320         free(error);
1321
1322         error = ipv6_parse_cidr(orig_prefix, &ipv6, &plen);
1323         if (error) {
1324             free(error);
1325             return NULL;
1326         }
1327         return normalize_ipv6_prefix(ipv6, plen);
1328     }
1329 }
1330 \f
1331 static void
1332 nbctl_lr_route_add(struct ctl_context *ctx)
1333 {
1334     const struct nbrec_logical_router *lr;
1335     lr = lr_by_name_or_uuid(ctx, ctx->argv[1], true);
1336     char *prefix, *next_hop;
1337
1338     prefix = normalize_prefix_str(ctx->argv[2]);
1339     if (!prefix) {
1340         ctl_fatal("bad prefix argument: %s", ctx->argv[2]);
1341     }
1342
1343     next_hop = normalize_prefix_str(ctx->argv[3]);
1344     if (!next_hop) {
1345         ctl_fatal("bad next hop argument: %s", ctx->argv[3]);
1346     }
1347
1348     if (strchr(prefix, '.')) {
1349         ovs_be32 hop_ipv4;
1350         if (!ip_parse(ctx->argv[3], &hop_ipv4)) {
1351             ctl_fatal("bad IPv4 nexthop argument: %s", ctx->argv[3]);
1352         }
1353     } else {
1354         struct in6_addr hop_ipv6;
1355         if (!ipv6_parse(ctx->argv[3], &hop_ipv6)) {
1356             ctl_fatal("bad IPv6 nexthop argument: %s", ctx->argv[3]);
1357         }
1358     }
1359
1360     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1361     for (int i = 0; i < lr->n_static_routes; i++) {
1362         const struct nbrec_logical_router_static_route *route
1363             = lr->static_routes[i];
1364         char *rt_prefix;
1365
1366         rt_prefix = normalize_prefix_str(lr->static_routes[i]->ip_prefix);
1367         if (!rt_prefix) {
1368             /* Ignore existing prefix we couldn't parse. */
1369             continue;
1370         }
1371
1372         if (strcmp(rt_prefix, prefix)) {
1373             free(rt_prefix);
1374             continue;
1375         }
1376
1377         if (!may_exist) {
1378             ctl_fatal("duplicate prefix: %s", prefix);
1379         }
1380
1381         /* Update the next hop for an existing route. */
1382         nbrec_logical_router_verify_static_routes(lr);
1383         nbrec_logical_router_static_route_verify_ip_prefix(route);
1384         nbrec_logical_router_static_route_verify_nexthop(route);
1385         nbrec_logical_router_static_route_set_ip_prefix(route, prefix);
1386         nbrec_logical_router_static_route_set_nexthop(route, next_hop);
1387         if (ctx->argc == 5) {
1388             nbrec_logical_router_static_route_set_output_port(route,
1389                                                               ctx->argv[4]);
1390         }
1391         free(rt_prefix);
1392         free(next_hop);
1393         free(prefix);
1394         return;
1395     }
1396
1397     struct nbrec_logical_router_static_route *route;
1398     route = nbrec_logical_router_static_route_insert(ctx->txn);
1399     nbrec_logical_router_static_route_set_ip_prefix(route, prefix);
1400     nbrec_logical_router_static_route_set_nexthop(route, next_hop);
1401     if (ctx->argc == 5) {
1402         nbrec_logical_router_static_route_set_output_port(route, ctx->argv[4]);
1403     }
1404
1405     nbrec_logical_router_verify_static_routes(lr);
1406     struct nbrec_logical_router_static_route **new_routes
1407         = xmalloc(sizeof *new_routes * (lr->n_static_routes + 1));
1408     memcpy(new_routes, lr->static_routes,
1409            sizeof *new_routes * lr->n_static_routes);
1410     new_routes[lr->n_static_routes] = route;
1411     nbrec_logical_router_set_static_routes(lr, new_routes,
1412                                            lr->n_static_routes + 1);
1413     free(new_routes);
1414     free(next_hop);
1415     free(prefix);
1416 }
1417
1418 static void
1419 nbctl_lr_route_del(struct ctl_context *ctx)
1420 {
1421     const struct nbrec_logical_router *lr;
1422     lr = lr_by_name_or_uuid(ctx, ctx->argv[1], true);
1423
1424     if (ctx->argc == 2) {
1425         /* If a prefix is not specified, delete all routes. */
1426         nbrec_logical_router_set_static_routes(lr, NULL, 0);
1427         return;
1428     }
1429
1430     char *prefix = normalize_prefix_str(ctx->argv[2]);
1431     if (!prefix) {
1432         ctl_fatal("bad prefix argument: %s", ctx->argv[2]);
1433     }
1434
1435     for (int i = 0; i < lr->n_static_routes; i++) {
1436         char *rt_prefix = normalize_prefix_str(lr->static_routes[i]->ip_prefix);
1437         if (!rt_prefix) {
1438             /* Ignore existing prefix we couldn't parse. */
1439             continue;
1440         }
1441
1442         if (!strcmp(prefix, rt_prefix)) {
1443             struct nbrec_logical_router_static_route **new_routes
1444                 = xmemdup(lr->static_routes,
1445                           sizeof *new_routes * lr->n_static_routes);
1446
1447             new_routes[i] = lr->static_routes[lr->n_static_routes - 1];
1448             nbrec_logical_router_verify_static_routes(lr);
1449             nbrec_logical_router_set_static_routes(lr, new_routes,
1450                                                  lr->n_static_routes - 1);
1451             free(new_routes);
1452             free(rt_prefix);
1453             free(prefix);
1454             return;
1455         }
1456         free(rt_prefix);
1457     }
1458
1459     if (!shash_find(&ctx->options, "--if-exists")) {
1460         ctl_fatal("no matching prefix: %s", prefix);
1461     }
1462     free(prefix);
1463 }
1464 \f
1465 static const struct nbrec_logical_router_port *
1466 lrp_by_name_or_uuid(struct ctl_context *ctx, const char *id, bool must_exist)
1467 {
1468     const struct nbrec_logical_router_port *lrp = NULL;
1469
1470     struct uuid lrp_uuid;
1471     bool is_uuid = uuid_from_string(&lrp_uuid, id);
1472     if (is_uuid) {
1473         lrp = nbrec_logical_router_port_get_for_uuid(ctx->idl, &lrp_uuid);
1474     }
1475
1476     if (!lrp) {
1477         NBREC_LOGICAL_ROUTER_PORT_FOR_EACH(lrp, ctx->idl) {
1478             if (!strcmp(lrp->name, id)) {
1479                 break;
1480             }
1481         }
1482     }
1483
1484     if (!lrp && must_exist) {
1485         ctl_fatal("%s: port %s not found", id, is_uuid ? "UUID" : "name");
1486     }
1487
1488     return lrp;
1489 }
1490
1491 /* Returns the logical router that contains 'lrp'. */
1492 static const struct nbrec_logical_router *
1493 lrp_to_lr(const struct ovsdb_idl *idl,
1494                const struct nbrec_logical_router_port *lrp)
1495 {
1496     const struct nbrec_logical_router *lr;
1497     NBREC_LOGICAL_ROUTER_FOR_EACH (lr, idl) {
1498         for (size_t i = 0; i < lr->n_ports; i++) {
1499             if (lr->ports[i] == lrp) {
1500                 return lr;
1501             }
1502         }
1503     }
1504
1505     /* Can't happen because of the database schema */
1506     ctl_fatal("port %s is not part of any logical router",
1507               lrp->name);
1508 }
1509
1510 static const char *
1511 lr_get_name(const struct nbrec_logical_router *lr, char uuid_s[UUID_LEN + 1],
1512             size_t uuid_s_size)
1513 {
1514     if (lr->name[0]) {
1515         return lr->name;
1516     }
1517     snprintf(uuid_s, uuid_s_size, UUID_FMT, UUID_ARGS(&lr->header_.uuid));
1518     return uuid_s;
1519 }
1520
1521 static void
1522 nbctl_lrp_add(struct ctl_context *ctx)
1523 {
1524     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1525
1526     const struct nbrec_logical_router *lr;
1527     lr = lr_by_name_or_uuid(ctx, ctx->argv[1], true);
1528
1529     const char *lrp_name = ctx->argv[2];
1530     const char *mac = ctx->argv[3];
1531     const char **networks = (const char **) &ctx->argv[4];
1532
1533     int n_networks = ctx->argc - 4;
1534     for (int i = 4; i < ctx->argc; i++) {
1535         if (strchr(ctx->argv[i], '=')) {
1536             n_networks = i - 4;
1537             break;
1538         }
1539     }
1540
1541     if (!n_networks) {
1542         ctl_fatal("%s: router port requires specifying a network", lrp_name);
1543     }
1544
1545     char **settings = (char **) &ctx->argv[n_networks + 4];
1546     int n_settings = ctx->argc - 4 - n_networks;
1547
1548     const struct nbrec_logical_router_port *lrp;
1549     lrp = lrp_by_name_or_uuid(ctx, lrp_name, false);
1550     if (lrp) {
1551         if (!may_exist) {
1552             ctl_fatal("%s: a port with this name already exists",
1553                       lrp_name);
1554         }
1555
1556         const struct nbrec_logical_router *bound_lr;
1557         bound_lr = lrp_to_lr(ctx->idl, lrp);
1558         if (bound_lr != lr) {
1559             char uuid_s[UUID_LEN + 1];
1560             ctl_fatal("%s: port already exists but in router %s", lrp_name,
1561                       lr_get_name(bound_lr, uuid_s, sizeof uuid_s));
1562         }
1563
1564         if (strcmp(mac, lrp->mac)) {
1565             ctl_fatal("%s: port already exists with mac %s", lrp_name,
1566                       lrp->mac);
1567         }
1568
1569         struct sset new_networks = SSET_INITIALIZER(&new_networks);
1570         for (int i = 0; i < n_networks; i++) {
1571             sset_add(&new_networks, networks[i]);
1572         }
1573
1574         struct sset orig_networks = SSET_INITIALIZER(&orig_networks);
1575         sset_add_array(&orig_networks, lrp->networks, lrp->n_networks);
1576
1577         if (!sset_equals(&orig_networks, &new_networks)) {
1578             ctl_fatal("%s: port already exists with different network",
1579                       lrp_name);
1580         }
1581
1582         sset_destroy(&orig_networks);
1583         sset_destroy(&new_networks);
1584
1585         /* Special-case sanity-check of peer ports. */
1586         const char *peer = NULL;
1587         for (int i = 0; i < n_settings; i++) {
1588             if (!strncmp(settings[i], "peer=", 5)) {
1589                 peer = settings[i] + 5;
1590                 break;
1591             }
1592         }
1593
1594         if ((!peer != !lrp->peer) ||
1595                 (lrp->peer && strcmp(peer, lrp->peer))) {
1596             ctl_fatal("%s: port already exists with mismatching peer",
1597                       lrp_name);
1598         }
1599
1600         return;
1601     }
1602
1603     struct eth_addr ea;
1604     if (!ovs_scan(mac, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(ea))) {
1605         ctl_fatal("%s: invalid mac address %s", lrp_name, mac);
1606     }
1607
1608     for (int i = 0; i < n_networks; i++) {
1609         ovs_be32 ipv4;
1610         unsigned int plen;
1611         char *error = ip_parse_cidr(networks[i], &ipv4, &plen);
1612         if (error) {
1613             free(error);
1614             struct in6_addr ipv6;
1615             error = ipv6_parse_cidr(networks[i], &ipv6, &plen);
1616             if (error) {
1617                 free(error);
1618                 ctl_fatal("%s: invalid network address: %s", lrp_name,
1619                           networks[i]);
1620             }
1621         }
1622     }
1623
1624     /* Create the logical port. */
1625     lrp = nbrec_logical_router_port_insert(ctx->txn);
1626     nbrec_logical_router_port_set_name(lrp, lrp_name);
1627     nbrec_logical_router_port_set_mac(lrp, mac);
1628     nbrec_logical_router_port_set_networks(lrp, networks, n_networks);
1629
1630     for (int i = 0; i < n_settings; i++) {
1631         ctl_set_column("Logical_Router_Port", &lrp->header_, settings[i],
1632                        ctx->symtab);
1633     }
1634
1635     /* Insert the logical port into the logical router. */
1636     nbrec_logical_router_verify_ports(lr);
1637     struct nbrec_logical_router_port **new_ports = xmalloc(sizeof *new_ports *
1638                                                         (lr->n_ports + 1));
1639     memcpy(new_ports, lr->ports, sizeof *new_ports * lr->n_ports);
1640     new_ports[lr->n_ports] = CONST_CAST(struct nbrec_logical_router_port *,
1641                                              lrp);
1642     nbrec_logical_router_set_ports(lr, new_ports, lr->n_ports + 1);
1643     free(new_ports);
1644 }
1645
1646 /* Removes logical router port 'lr->ports[idx]'. */
1647 static void
1648 remove_lrp(const struct nbrec_logical_router *lr, size_t idx)
1649 {
1650     const struct nbrec_logical_router_port *lrp = lr->ports[idx];
1651
1652     /* First remove 'lrp' from the array of ports.  This is what will
1653      * actually cause the logical port to be deleted when the transaction is
1654      * sent to the database server (due to garbage collection). */
1655     struct nbrec_logical_router_port **new_ports
1656         = xmemdup(lr->ports, sizeof *new_ports * lr->n_ports);
1657     new_ports[idx] = new_ports[lr->n_ports - 1];
1658     nbrec_logical_router_verify_ports(lr);
1659     nbrec_logical_router_set_ports(lr, new_ports, lr->n_ports - 1);
1660     free(new_ports);
1661
1662     /* Delete 'lrp' from the IDL.  This won't have a real effect on
1663      * the database server (the IDL will suppress it in fact) but it
1664      * means that it won't show up when we iterate with
1665      * NBREC_LOGICAL_ROUTER_PORT_FOR_EACH later. */
1666     nbrec_logical_router_port_delete(lrp);
1667 }
1668
1669 static void
1670 nbctl_lrp_del(struct ctl_context *ctx)
1671 {
1672     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1673     const struct nbrec_logical_router_port *lrp;
1674
1675     lrp = lrp_by_name_or_uuid(ctx, ctx->argv[1], must_exist);
1676     if (!lrp) {
1677         return;
1678     }
1679
1680     /* Find the router that contains 'lrp', then delete it. */
1681     const struct nbrec_logical_router *lr;
1682     NBREC_LOGICAL_ROUTER_FOR_EACH (lr, ctx->idl) {
1683         for (size_t i = 0; i < lr->n_ports; i++) {
1684             if (lr->ports[i] == lrp) {
1685                 remove_lrp(lr, i);
1686                 return;
1687             }
1688         }
1689     }
1690
1691     /* Can't happen because of the database schema. */
1692     ctl_fatal("logical port %s is not part of any logical router",
1693               ctx->argv[1]);
1694 }
1695
1696 /* Print a list of logical router ports. */
1697 static void
1698 nbctl_lrp_list(struct ctl_context *ctx)
1699 {
1700     const char *id = ctx->argv[1];
1701     const struct nbrec_logical_router *lr;
1702     struct smap lrps;
1703     size_t i;
1704
1705     lr = lr_by_name_or_uuid(ctx, id, true);
1706
1707     smap_init(&lrps);
1708     for (i = 0; i < lr->n_ports; i++) {
1709         const struct nbrec_logical_router_port *lrp = lr->ports[i];
1710         smap_add_format(&lrps, lrp->name, UUID_FMT " (%s)",
1711                         UUID_ARGS(&lrp->header_.uuid), lrp->name);
1712     }
1713     const struct smap_node **nodes = smap_sort(&lrps);
1714     for (i = 0; i < smap_count(&lrps); i++) {
1715         const struct smap_node *node = nodes[i];
1716         ds_put_format(&ctx->output, "%s\n", node->value);
1717     }
1718     smap_destroy(&lrps);
1719     free(nodes);
1720 }
1721
1722 /* Set the logical router port admin-enabled state. */
1723 static void
1724 nbctl_lrp_set_enabled(struct ctl_context *ctx)
1725 {
1726     const char *id = ctx->argv[1];
1727     const char *state = ctx->argv[2];
1728     const struct nbrec_logical_router_port *lrp;
1729
1730     lrp = lrp_by_name_or_uuid(ctx, id, true);
1731     if (!lrp) {
1732         return;
1733     }
1734
1735     bool enabled = parse_enabled(state);
1736     nbrec_logical_router_port_set_enabled(lrp, &enabled, 1);
1737 }
1738
1739 /* Print admin-enabled state for logical router port. */
1740 static void
1741 nbctl_lrp_get_enabled(struct ctl_context *ctx)
1742 {
1743     const char *id = ctx->argv[1];
1744     const struct nbrec_logical_router_port *lrp;
1745
1746     lrp = lrp_by_name_or_uuid(ctx, id, true);
1747     if (!lrp) {
1748         return;
1749     }
1750
1751     ds_put_format(&ctx->output, "%s\n",
1752                   !lrp->enabled ||
1753                   *lrp->enabled ? "enabled" : "disabled");
1754 }
1755 \f
1756 struct ipv4_route {
1757     int plen;
1758     ovs_be32 addr;
1759     const struct nbrec_logical_router_static_route *route;
1760 };
1761
1762 static int
1763 ipv4_route_cmp(const void *route1_, const void *route2_)
1764 {
1765     const struct ipv4_route *route1p = route1_;
1766     const struct ipv4_route *route2p = route2_;
1767
1768     if (route1p->plen != route2p->plen) {
1769         return route1p->plen > route2p->plen ? -1 : 1;
1770     } else if (route1p->addr != route2p->addr) {
1771         return ntohl(route1p->addr) < ntohl(route2p->addr) ? -1 : 1;
1772     } else {
1773         return 0;
1774     }
1775 }
1776
1777 struct ipv6_route {
1778     int plen;
1779     struct in6_addr addr;
1780     const struct nbrec_logical_router_static_route *route;
1781 };
1782
1783 static int
1784 ipv6_route_cmp(const void *route1_, const void *route2_)
1785 {
1786     const struct ipv6_route *route1p = route1_;
1787     const struct ipv6_route *route2p = route2_;
1788
1789     if (route1p->plen != route2p->plen) {
1790         return route1p->plen > route2p->plen ? -1 : 1;
1791     }
1792     return memcmp(&route1p->addr, &route2p->addr, sizeof(route1p->addr));
1793 }
1794
1795 static void
1796 print_route(const struct nbrec_logical_router_static_route *route, struct ds *s)
1797 {
1798
1799     char *prefix = normalize_prefix_str(route->ip_prefix);
1800     char *next_hop = normalize_prefix_str(route->nexthop);
1801     ds_put_format(s, "%25s %25s", prefix, next_hop);
1802     free(prefix);
1803     free(next_hop);
1804
1805     if (route->output_port) {
1806         ds_put_format(s, " %s", route->output_port);
1807     }
1808     ds_put_char(s, '\n');
1809 }
1810
1811 static void
1812 nbctl_lr_route_list(struct ctl_context *ctx)
1813 {
1814     const struct nbrec_logical_router *lr;
1815     struct ipv4_route *ipv4_routes;
1816     struct ipv6_route *ipv6_routes;
1817     size_t n_ipv4_routes = 0;
1818     size_t n_ipv6_routes = 0;
1819
1820     lr = lr_by_name_or_uuid(ctx, ctx->argv[1], true);
1821
1822     ipv4_routes = xmalloc(sizeof *ipv4_routes * lr->n_static_routes);
1823     ipv6_routes = xmalloc(sizeof *ipv6_routes * lr->n_static_routes);
1824
1825     for (int i = 0; i < lr->n_static_routes; i++) {
1826         const struct nbrec_logical_router_static_route *route
1827             = lr->static_routes[i];
1828         unsigned int plen;
1829         ovs_be32 ipv4;
1830         char *error;
1831
1832         error = ip_parse_cidr(route->ip_prefix, &ipv4, &plen);
1833         if (!error) {
1834             ipv4_routes[n_ipv4_routes].plen = plen;
1835             ipv4_routes[n_ipv4_routes].addr = ipv4;
1836             ipv4_routes[n_ipv4_routes].route = route;
1837             n_ipv4_routes++;
1838         } else {
1839             free(error);
1840
1841             struct in6_addr ipv6;
1842             error = ipv6_parse_cidr(route->ip_prefix, &ipv6, &plen);
1843             if (!error) {
1844                 ipv6_routes[n_ipv6_routes].plen = plen;
1845                 ipv6_routes[n_ipv6_routes].addr = ipv6;
1846                 ipv6_routes[n_ipv6_routes].route = route;
1847                 n_ipv6_routes++;
1848             } else {
1849                 /* Invalid prefix. */
1850                 VLOG_WARN("router "UUID_FMT" (%s) has invalid prefix: %s",
1851                           UUID_ARGS(&lr->header_.uuid), lr->name,
1852                           route->ip_prefix);
1853                 free(error);
1854                 continue;
1855             }
1856         }
1857     }
1858
1859     qsort(ipv4_routes, n_ipv4_routes, sizeof *ipv4_routes, ipv4_route_cmp);
1860     qsort(ipv6_routes, n_ipv6_routes, sizeof *ipv6_routes, ipv6_route_cmp);
1861
1862     if (n_ipv4_routes) {
1863         ds_put_cstr(&ctx->output, "IPv4 Routes\n");
1864     }
1865     for (int i = 0; i < n_ipv4_routes; i++) {
1866         print_route(ipv4_routes[i].route, &ctx->output);
1867     }
1868
1869     if (n_ipv6_routes) {
1870         ds_put_format(&ctx->output, "%sIPv6 Routes\n",
1871                       n_ipv4_routes ?  "\n" : "");
1872     }
1873     for (int i = 0; i < n_ipv6_routes; i++) {
1874         print_route(ipv6_routes[i].route, &ctx->output);
1875     }
1876
1877     free(ipv4_routes);
1878     free(ipv6_routes);
1879 }
1880
1881 static const struct ctl_table_class tables[] = {
1882     {&nbrec_table_logical_switch,
1883      {{&nbrec_table_logical_switch, &nbrec_logical_switch_col_name, NULL},
1884       {NULL, NULL, NULL}}},
1885
1886     {&nbrec_table_logical_switch_port,
1887      {{&nbrec_table_logical_switch_port, &nbrec_logical_switch_port_col_name,
1888        NULL},
1889       {NULL, NULL, NULL}}},
1890
1891     {&nbrec_table_acl,
1892      {{NULL, NULL, NULL},
1893       {NULL, NULL, NULL}}},
1894
1895     {&nbrec_table_load_balancer,
1896      {{NULL, NULL, NULL},
1897       {NULL, NULL, NULL}}},
1898
1899     {&nbrec_table_logical_router,
1900      {{&nbrec_table_logical_router, &nbrec_logical_router_col_name, NULL},
1901       {NULL, NULL, NULL}}},
1902
1903     {&nbrec_table_logical_router_port,
1904      {{&nbrec_table_logical_router_port, &nbrec_logical_router_port_col_name,
1905        NULL},
1906       {NULL, NULL, NULL}}},
1907
1908     {&nbrec_table_logical_router_static_route,
1909      {{&nbrec_table_logical_router_static_route, NULL,
1910        NULL},
1911       {NULL, NULL, NULL}}},
1912
1913     {&nbrec_table_nat,
1914      {{&nbrec_table_nat, NULL,
1915        NULL},
1916       {NULL, NULL, NULL}}},
1917
1918     {&nbrec_table_address_set,
1919      {{&nbrec_table_address_set, &nbrec_address_set_col_name, NULL},
1920       {NULL, NULL, NULL}}},
1921
1922     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1923 };
1924 \f
1925 static void
1926 run_prerequisites(struct ctl_command *commands, size_t n_commands,
1927                   struct ovsdb_idl *idl)
1928 {
1929     struct ctl_command *c;
1930
1931     for (c = commands; c < &commands[n_commands]; c++) {
1932         if (c->syntax->prerequisites) {
1933             struct ctl_context ctx;
1934
1935             ds_init(&c->output);
1936             c->table = NULL;
1937
1938             ctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
1939             (c->syntax->prerequisites)(&ctx);
1940             ctl_context_done(&ctx, c);
1941
1942             ovs_assert(!c->output.string);
1943             ovs_assert(!c->table);
1944         }
1945     }
1946 }
1947
1948 static bool
1949 do_nbctl(const char *args, struct ctl_command *commands, size_t n_commands,
1950          struct ovsdb_idl *idl)
1951 {
1952     struct ovsdb_idl_txn *txn;
1953     enum ovsdb_idl_txn_status status;
1954     struct ovsdb_symbol_table *symtab;
1955     struct ctl_context ctx;
1956     struct ctl_command *c;
1957     struct shash_node *node;
1958     char *error = NULL;
1959
1960     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
1961     if (dry_run) {
1962         ovsdb_idl_txn_set_dry_run(txn);
1963     }
1964
1965     ovsdb_idl_txn_add_comment(txn, "ovs-nbctl: %s", args);
1966
1967     symtab = ovsdb_symbol_table_create();
1968     for (c = commands; c < &commands[n_commands]; c++) {
1969         ds_init(&c->output);
1970         c->table = NULL;
1971     }
1972     ctl_context_init(&ctx, NULL, idl, txn, symtab, NULL);
1973     for (c = commands; c < &commands[n_commands]; c++) {
1974         ctl_context_init_command(&ctx, c);
1975         if (c->syntax->run) {
1976             (c->syntax->run)(&ctx);
1977         }
1978         ctl_context_done_command(&ctx, c);
1979
1980         if (ctx.try_again) {
1981             ctl_context_done(&ctx, NULL);
1982             goto try_again;
1983         }
1984     }
1985     ctl_context_done(&ctx, NULL);
1986
1987     SHASH_FOR_EACH (node, &symtab->sh) {
1988         struct ovsdb_symbol *symbol = node->data;
1989         if (!symbol->created) {
1990             ctl_fatal("row id \"%s\" is referenced but never created (e.g. "
1991                       "with \"-- --id=%s create ...\")",
1992                       node->name, node->name);
1993         }
1994         if (!symbol->strong_ref) {
1995             if (!symbol->weak_ref) {
1996                 VLOG_WARN("row id \"%s\" was created but no reference to it "
1997                           "was inserted, so it will not actually appear in "
1998                           "the database", node->name);
1999             } else {
2000                 VLOG_WARN("row id \"%s\" was created but only a weak "
2001                           "reference to it was inserted, so it will not "
2002                           "actually appear in the database", node->name);
2003             }
2004         }
2005     }
2006
2007     status = ovsdb_idl_txn_commit_block(txn);
2008     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
2009         for (c = commands; c < &commands[n_commands]; c++) {
2010             if (c->syntax->postprocess) {
2011                 ctl_context_init(&ctx, c, idl, txn, symtab, NULL);
2012                 (c->syntax->postprocess)(&ctx);
2013                 ctl_context_done(&ctx, c);
2014             }
2015         }
2016     }
2017     error = xstrdup(ovsdb_idl_txn_get_error(txn));
2018
2019     switch (status) {
2020     case TXN_UNCOMMITTED:
2021     case TXN_INCOMPLETE:
2022         OVS_NOT_REACHED();
2023
2024     case TXN_ABORTED:
2025         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2026         ctl_fatal("transaction aborted");
2027
2028     case TXN_UNCHANGED:
2029     case TXN_SUCCESS:
2030         break;
2031
2032     case TXN_TRY_AGAIN:
2033         goto try_again;
2034
2035     case TXN_ERROR:
2036         ctl_fatal("transaction error: %s", error);
2037
2038     case TXN_NOT_LOCKED:
2039         /* Should not happen--we never call ovsdb_idl_set_lock(). */
2040         ctl_fatal("database not locked");
2041
2042     default:
2043         OVS_NOT_REACHED();
2044     }
2045     free(error);
2046
2047     ovsdb_symbol_table_destroy(symtab);
2048
2049     for (c = commands; c < &commands[n_commands]; c++) {
2050         struct ds *ds = &c->output;
2051
2052         if (c->table) {
2053             table_print(c->table, &table_style);
2054         } else if (oneline) {
2055             size_t j;
2056
2057             ds_chomp(ds, '\n');
2058             for (j = 0; j < ds->length; j++) {
2059                 int ch = ds->string[j];
2060                 switch (ch) {
2061                 case '\n':
2062                     fputs("\\n", stdout);
2063                     break;
2064
2065                 case '\\':
2066                     fputs("\\\\", stdout);
2067                     break;
2068
2069                 default:
2070                     putchar(ch);
2071                 }
2072             }
2073             putchar('\n');
2074         } else {
2075             fputs(ds_cstr(ds), stdout);
2076         }
2077         ds_destroy(&c->output);
2078         table_destroy(c->table);
2079         free(c->table);
2080
2081         shash_destroy_free_data(&c->options);
2082     }
2083     free(commands);
2084     ovsdb_idl_txn_destroy(txn);
2085     ovsdb_idl_destroy(idl);
2086
2087     return true;
2088
2089 try_again:
2090     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
2091      * resources and return so that the caller can try again. */
2092     if (txn) {
2093         ovsdb_idl_txn_abort(txn);
2094         ovsdb_idl_txn_destroy(txn);
2095         the_idl_txn = NULL;
2096     }
2097     ovsdb_symbol_table_destroy(symtab);
2098     for (c = commands; c < &commands[n_commands]; c++) {
2099         ds_destroy(&c->output);
2100         table_destroy(c->table);
2101         free(c->table);
2102     }
2103     free(error);
2104     return false;
2105 }
2106
2107 /* Frees the current transaction and the underlying IDL and then calls
2108  * exit(status).
2109  *
2110  * Freeing the transaction and the IDL is not strictly necessary, but it makes
2111  * for a clean memory leak report from valgrind in the normal case.  That makes
2112  * it easier to notice real memory leaks. */
2113 static void
2114 nbctl_exit(int status)
2115 {
2116     if (the_idl_txn) {
2117         ovsdb_idl_txn_abort(the_idl_txn);
2118         ovsdb_idl_txn_destroy(the_idl_txn);
2119     }
2120     ovsdb_idl_destroy(the_idl);
2121     exit(status);
2122 }
2123
2124 static const struct ctl_command_syntax nbctl_commands[] = {
2125     { "show", 0, 1, "[SWITCH]", NULL, nbctl_show, NULL, "", RO },
2126
2127     /* logical switch commands. */
2128     { "ls-add", 0, 1, "[SWITCH]", NULL, nbctl_ls_add, NULL,
2129       "--may-exist,--add-duplicate", RW },
2130     { "ls-del", 1, 1, "SWITCH", NULL, nbctl_ls_del, NULL, "--if-exists", RW },
2131     { "ls-list", 0, 0, "", NULL, nbctl_ls_list, NULL, "", RO },
2132
2133     /* acl commands. */
2134     { "acl-add", 5, 5, "SWITCH DIRECTION PRIORITY MATCH ACTION", NULL,
2135       nbctl_acl_add, NULL, "--log", RW },
2136     { "acl-del", 1, 4, "SWITCH [DIRECTION [PRIORITY MATCH]]", NULL,
2137       nbctl_acl_del, NULL, "", RW },
2138     { "acl-list", 1, 1, "SWITCH", NULL, nbctl_acl_list, NULL, "", RO },
2139
2140     /* logical switch port commands. */
2141     { "lsp-add", 2, 4, "SWITCH PORT [PARENT] [TAG]", NULL, nbctl_lsp_add,
2142       NULL, "--may-exist", RW },
2143     { "lsp-del", 1, 1, "PORT", NULL, nbctl_lsp_del, NULL, "--if-exists", RW },
2144     { "lsp-list", 1, 1, "SWITCH", NULL, nbctl_lsp_list, NULL, "", RO },
2145     { "lsp-get-parent", 1, 1, "PORT", NULL, nbctl_lsp_get_parent, NULL,
2146       "", RO },
2147     { "lsp-get-tag", 1, 1, "PORT", NULL, nbctl_lsp_get_tag, NULL, "", RO },
2148     { "lsp-set-addresses", 1, INT_MAX, "PORT [ADDRESS]...", NULL,
2149       nbctl_lsp_set_addresses, NULL, "", RW },
2150     { "lsp-get-addresses", 1, 1, "PORT", NULL, nbctl_lsp_get_addresses, NULL,
2151       "", RO },
2152     { "lsp-set-port-security", 0, INT_MAX, "PORT [ADDRS]...", NULL,
2153       nbctl_lsp_set_port_security, NULL, "", RW },
2154     { "lsp-get-port-security", 1, 1, "PORT", NULL,
2155       nbctl_lsp_get_port_security, NULL, "", RO },
2156     { "lsp-get-up", 1, 1, "PORT", NULL, nbctl_lsp_get_up, NULL, "", RO },
2157     { "lsp-set-enabled", 2, 2, "PORT STATE", NULL, nbctl_lsp_set_enabled,
2158       NULL, "", RW },
2159     { "lsp-get-enabled", 1, 1, "PORT", NULL, nbctl_lsp_get_enabled, NULL,
2160       "", RO },
2161     { "lsp-set-type", 2, 2, "PORT TYPE", NULL, nbctl_lsp_set_type, NULL,
2162       "", RW },
2163     { "lsp-get-type", 1, 1, "PORT", NULL, nbctl_lsp_get_type, NULL, "", RO },
2164     { "lsp-set-options", 1, INT_MAX, "PORT KEY=VALUE [KEY=VALUE]...", NULL,
2165       nbctl_lsp_set_options, NULL, "", RW },
2166     { "lsp-get-options", 1, 1, "PORT", NULL, nbctl_lsp_get_options, NULL,
2167       "", RO },
2168
2169     /* logical router commands. */
2170     { "lr-add", 0, 1, "[ROUTER]", NULL, nbctl_lr_add, NULL,
2171       "--may-exist,--add-duplicate", RW },
2172     { "lr-del", 1, 1, "ROUTER", NULL, nbctl_lr_del, NULL, "--if-exists", RW },
2173     { "lr-list", 0, 0, "", NULL, nbctl_lr_list, NULL, "", RO },
2174
2175     /* logical router port commands. */
2176     { "lrp-add", 4, INT_MAX,
2177       "ROUTER PORT MAC NETWORK... [COLUMN[:KEY]=VALUE]...",
2178       NULL, nbctl_lrp_add, NULL, "--may-exist", RW },
2179     { "lrp-del", 1, 1, "PORT", NULL, nbctl_lrp_del, NULL, "--if-exists", RW },
2180     { "lrp-list", 1, 1, "ROUTER", NULL, nbctl_lrp_list, NULL, "", RO },
2181     { "lrp-set-enabled", 2, 2, "PORT STATE", NULL, nbctl_lrp_set_enabled,
2182       NULL, "", RW },
2183     { "lrp-get-enabled", 1, 1, "PORT", NULL, nbctl_lrp_get_enabled,
2184       NULL, "", RO },
2185
2186     /* logical router route commands. */
2187     { "lr-route-add", 3, 4, "ROUTER PREFIX NEXTHOP [PORT]", NULL,
2188       nbctl_lr_route_add, NULL, "--may-exist", RW },
2189     { "lr-route-del", 1, 2, "ROUTER [PREFIX]", NULL, nbctl_lr_route_del,
2190       NULL, "--if-exists", RW },
2191     { "lr-route-list", 1, 1, "ROUTER", NULL, nbctl_lr_route_list, NULL,
2192       "", RO },
2193
2194     {NULL, 0, 0, NULL, NULL, NULL, NULL, "", RO},
2195 };
2196
2197 /* Registers nbctl and common db commands. */
2198 static void
2199 nbctl_cmd_init(void)
2200 {
2201     ctl_init(tables, NULL, nbctl_exit);
2202     ctl_register_commands(nbctl_commands);
2203 }