ovn-northd: Always use semicolons for each action.
[cascardo/ovs.git] / ovn / northd / ovn-northd.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 <stdlib.h>
19 #include <stdio.h>
20
21 #include "command-line.h"
22 #include "daemon.h"
23 #include "dirs.h"
24 #include "dynamic-string.h"
25 #include "fatal-signal.h"
26 #include "hash.h"
27 #include "hmap.h"
28 #include "json.h"
29 #include "ovn/lib/lex.h"
30 #include "ovn/ovn-nb-idl.h"
31 #include "ovn/ovn-sb-idl.h"
32 #include "poll-loop.h"
33 #include "stream.h"
34 #include "stream-ssl.h"
35 #include "util.h"
36 #include "uuid.h"
37 #include "openvswitch/vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(ovn_northd);
40
41 struct northd_context {
42     struct ovsdb_idl *ovnnb_idl;
43     struct ovsdb_idl *ovnsb_idl;
44     struct ovsdb_idl_txn *ovnnb_txn;
45     struct ovsdb_idl_txn *ovnsb_txn;
46 };
47
48 static const char *ovnnb_db;
49 static const char *ovnsb_db;
50
51 static const char *default_db(void);
52
53 static void
54 usage(void)
55 {
56     printf("\
57 %s: OVN northbound management daemon\n\
58 usage: %s [OPTIONS]\n\
59 \n\
60 Options:\n\
61   --ovnnb-db=DATABASE       connect to ovn-nb database at DATABASE\n\
62                             (default: %s)\n\
63   --ovnsb-db=DATABASE       connect to ovn-sb database at DATABASE\n\
64                             (default: %s)\n\
65   -h, --help                display this help message\n\
66   -o, --options             list available options\n\
67   -V, --version             display version information\n\
68 ", program_name, program_name, default_db(), default_db());
69     daemon_usage();
70     vlog_usage();
71     stream_usage("database", true, true, false);
72 }
73 \f
74 static int
75 compare_strings(const void *a_, const void *b_)
76 {
77     char *const *a = a_;
78     char *const *b = b_;
79     return strcmp(*a, *b);
80 }
81
82 /*
83  * Determine whether 2 arrays of MAC addresses are the same.  It's possible that
84  * the lists could be *very* long and this check is being done a lot (every
85  * time the OVN_Northbound database changes).
86  */
87 static bool
88 macs_equal(char **binding_macs_, size_t b_n_macs,
89            char **lport_macs_, size_t l_n_macs)
90 {
91     char **binding_macs, **lport_macs;
92     size_t bytes, i;
93
94     if (b_n_macs != l_n_macs) {
95         return false;
96     }
97
98     bytes = b_n_macs * sizeof binding_macs_[0];
99     binding_macs = xmalloc(bytes);
100     lport_macs = xmalloc(bytes);
101
102     memcpy(binding_macs, binding_macs_, bytes);
103     memcpy(lport_macs, lport_macs_, bytes);
104
105     qsort(binding_macs, b_n_macs, sizeof binding_macs[0], compare_strings);
106     qsort(lport_macs, l_n_macs, sizeof lport_macs[0], compare_strings);
107
108     for (i = 0; i < b_n_macs; i++) {
109         if (strcmp(binding_macs[i], lport_macs[i])) {
110             break;
111         }
112     }
113
114     free(binding_macs);
115     free(lport_macs);
116
117     return (i == b_n_macs) ? true : false;
118 }
119 \f
120 /* Pipeline generation.
121  *
122  * This code generates the Pipeline table in the southbound database, as a
123  * function of most of the northbound database.
124  */
125
126 /* Enough context to add a Pipeline row, using pipeline_add(). */
127 struct pipeline_ctx {
128     /* From northd_context. */
129     struct ovsdb_idl *ovnsb_idl;
130     struct ovsdb_idl_txn *ovnsb_txn;
131
132     /* Contains "struct pipeline_hash_node"s.  Used to figure out what existing
133      * Pipeline rows should be deleted: we index all of the Pipeline rows into
134      * this data structure, then as existing rows are generated we remove them.
135      * After generating all the rows, any remaining in 'pipeline_hmap' must be
136      * deleted from the database. */
137     struct hmap pipeline_hmap;
138 };
139
140 /* A row in the Pipeline table, indexed by its full contents, */
141 struct pipeline_hash_node {
142     struct hmap_node node;
143     const struct sbrec_pipeline *pipeline;
144 };
145
146 static size_t
147 pipeline_hash(const struct uuid *logical_datapath, uint8_t table_id,
148               uint16_t priority, const char *match, const char *actions)
149 {
150     size_t hash = uuid_hash(logical_datapath);
151     hash = hash_2words((table_id << 16) | priority, hash);
152     hash = hash_string(match, hash);
153     return hash_string(actions, hash);
154 }
155
156 static size_t
157 pipeline_hash_rec(const struct sbrec_pipeline *pipeline)
158 {
159     return pipeline_hash(&pipeline->logical_datapath, pipeline->table_id,
160                          pipeline->priority, pipeline->match,
161                          pipeline->actions);
162 }
163
164 /* Adds a row with the specified contents to the Pipeline table. */
165 static void
166 pipeline_add(struct pipeline_ctx *ctx,
167              const struct nbrec_logical_switch *logical_datapath,
168              uint8_t table_id,
169              uint16_t priority,
170              const char *match,
171              const char *actions)
172 {
173     struct pipeline_hash_node *hash_node;
174
175     /* Check whether such a row already exists in the Pipeline table.  If so,
176      * remove it from 'ctx->pipeline_hmap' and we're done. */
177     HMAP_FOR_EACH_WITH_HASH (hash_node, node,
178                              pipeline_hash(&logical_datapath->header_.uuid,
179                                            table_id, priority, match, actions),
180                              &ctx->pipeline_hmap) {
181         const struct sbrec_pipeline *pipeline = hash_node->pipeline;
182         if (uuid_equals(&pipeline->logical_datapath,
183                         &logical_datapath->header_.uuid)
184             && pipeline->table_id == table_id
185             && pipeline->priority == priority
186             && !strcmp(pipeline->match, match)
187             && !strcmp(pipeline->actions, actions)) {
188             hmap_remove(&ctx->pipeline_hmap, &hash_node->node);
189             free(hash_node);
190             return;
191         }
192     }
193
194     /* No such Pipeline row.  Add one. */
195     const struct sbrec_pipeline *pipeline;
196     pipeline = sbrec_pipeline_insert(ctx->ovnsb_txn);
197     sbrec_pipeline_set_logical_datapath(pipeline,
198                                         logical_datapath->header_.uuid);
199     sbrec_pipeline_set_table_id(pipeline, table_id);
200     sbrec_pipeline_set_priority(pipeline, priority);
201     sbrec_pipeline_set_match(pipeline, match);
202     sbrec_pipeline_set_actions(pipeline, actions);
203 }
204
205 /* A single port security constraint.  This is a parsed version of a single
206  * member of the port_security column in the OVN_NB Logical_Port table.
207  *
208  * Each token has type LEX_T_END if that field is missing, otherwise
209  * LEX_T_INTEGER or LEX_T_MASKED_INTEGER. */
210 struct ps_constraint {
211     struct lex_token eth;
212     struct lex_token ip4;
213     struct lex_token ip6;
214 };
215
216 /* Parses a member of the port_security column 'ps' into 'c'.  Returns true if
217  * successful, false on syntax error. */
218 static bool
219 parse_port_security(const char *ps, struct ps_constraint *c)
220 {
221     c->eth.type = LEX_T_END;
222     c->ip4.type = LEX_T_END;
223     c->ip6.type = LEX_T_END;
224
225     struct lexer lexer;
226     lexer_init(&lexer, ps);
227     do {
228         if (lexer.token.type == LEX_T_INTEGER ||
229             lexer.token.type == LEX_T_MASKED_INTEGER) {
230             struct lex_token *t;
231
232             t = (lexer.token.format == LEX_F_IPV4 ? &c->ip4
233                  : lexer.token.format == LEX_F_IPV6 ? &c->ip6
234                  : lexer.token.format == LEX_F_ETHERNET ? &c->eth
235                  : NULL);
236             if (t) {
237                 if (t->type == LEX_T_END) {
238                     *t = lexer.token;
239                 } else {
240                     VLOG_INFO("%s: port_security has duplicate %s address",
241                               ps, lex_format_to_string(lexer.token.format));
242                 }
243                 lexer_get(&lexer);
244                 lexer_match(&lexer, LEX_T_COMMA);
245                 continue;
246             }
247         }
248
249         VLOG_INFO("%s: syntax error in port_security", ps);
250         lexer_destroy(&lexer);
251         return false;
252     } while (lexer.token.type != LEX_T_END);
253     lexer_destroy(&lexer);
254
255     return true;
256 }
257
258 /* Appends port security constraints on L2 address field 'eth_addr_field'
259  * (e.g. "eth.src" or "eth.dst") to 'match'.  'port_security', with
260  * 'n_port_security' elements, is the collection of port_security constraints
261  * from an OVN_NB Logical_Port row.
262  *
263  * (This is naive; it's not yet possible to express complete L2 and L3 port
264  * security constraints as a single Boolean expression.) */
265 static void
266 build_port_security(const char *eth_addr_field,
267                     char **port_security, size_t n_port_security,
268                     struct ds *match)
269 {
270     size_t base_len = match->length;
271     ds_put_format(match, " && %s == {", eth_addr_field);
272
273     size_t n = 0;
274     for (size_t i = 0; i < n_port_security; i++) {
275         struct ps_constraint c;
276         if (parse_port_security(port_security[i], &c)
277             && c.eth.type != LEX_T_END) {
278             lex_token_format(&c.eth, match);
279             ds_put_char(match, ' ');
280             n++;
281         }
282     }
283     ds_put_cstr(match, "}");
284
285     if (!n) {
286         match->length = base_len;
287     }
288 }
289
290 /* Updates the Pipeline table in the OVN_SB database, constructing its contents
291  * based on the OVN_NB database. */
292 static void
293 build_pipeline(struct northd_context *ctx)
294 {
295     struct pipeline_ctx pc = {
296         .ovnsb_idl = ctx->ovnsb_idl,
297         .ovnsb_txn = ctx->ovnsb_txn,
298         .pipeline_hmap = HMAP_INITIALIZER(&pc.pipeline_hmap)
299     };
300
301     /* Add all the Pipeline entries currently in the southbound database to
302      * 'pc.pipeline_hmap'.  We remove entries that we generate from the hmap,
303      * thus by the time we're done only entries that need to be removed
304      * remain. */
305     const struct sbrec_pipeline *pipeline;
306     SBREC_PIPELINE_FOR_EACH (pipeline, ctx->ovnsb_idl) {
307         struct pipeline_hash_node *hash_node = xzalloc(sizeof *hash_node);
308         hash_node->pipeline = pipeline;
309         hmap_insert(&pc.pipeline_hmap, &hash_node->node,
310                     pipeline_hash_rec(pipeline));
311     }
312
313     /* Table 0: Admission control framework. */
314     const struct nbrec_logical_switch *lswitch;
315     NBREC_LOGICAL_SWITCH_FOR_EACH (lswitch, ctx->ovnnb_idl) {
316         /* Logical VLANs not supported. */
317         pipeline_add(&pc, lswitch, 0, 100, "vlan.present", "drop;");
318
319         /* Broadcast/multicast source address is invalid. */
320         pipeline_add(&pc, lswitch, 0, 100, "eth.src[40]", "drop;");
321
322         /* Port security flows have priority 50 (see below) and will resubmit
323          * if packet source is acceptable. */
324
325         /* Otherwise drop the packet. */
326         pipeline_add(&pc, lswitch, 0, 0, "1", "drop;");
327     }
328
329     /* Table 0: Ingress port security. */
330     const struct nbrec_logical_port *lport;
331     NBREC_LOGICAL_PORT_FOR_EACH (lport, ctx->ovnnb_idl) {
332         struct ds match = DS_EMPTY_INITIALIZER;
333         ds_put_cstr(&match, "inport == ");
334         json_string_escape(lport->name, &match);
335         build_port_security("eth.src",
336                             lport->port_security, lport->n_port_security,
337                             &match);
338         pipeline_add(&pc, lport->lswitch, 0, 50, ds_cstr(&match), "resubmit;");
339         ds_destroy(&match);
340     }
341
342     /* Table 1: Destination lookup, broadcast and multicast handling (priority
343      * 100). */
344     NBREC_LOGICAL_SWITCH_FOR_EACH (lswitch, ctx->ovnnb_idl) {
345         struct ds actions;
346
347         ds_init(&actions);
348         NBREC_LOGICAL_PORT_FOR_EACH (lport, ctx->ovnnb_idl) {
349             if (lport->lswitch == lswitch) {
350                 ds_put_cstr(&actions, "outport = ");
351                 json_string_escape(lport->name, &actions);
352                 ds_put_cstr(&actions, "; resubmit; ");
353             }
354         }
355         ds_chomp(&actions, ' ');
356
357         pipeline_add(&pc, lswitch, 1, 100, "eth.dst[40]", ds_cstr(&actions));
358         ds_destroy(&actions);
359     }
360
361     /* Table 1: Destination lookup, unicast handling (priority 50),  */
362     struct ds unknown_actions = DS_EMPTY_INITIALIZER;
363     NBREC_LOGICAL_PORT_FOR_EACH (lport, ctx->ovnnb_idl) {
364         for (size_t i = 0; i < lport->n_macs; i++) {
365             uint8_t mac[ETH_ADDR_LEN];
366
367             if (eth_addr_from_string(lport->macs[i], mac)) {
368                 struct ds match, actions;
369
370                 ds_init(&match);
371                 ds_put_format(&match, "eth.dst == %s", lport->macs[i]);
372
373                 ds_init(&actions);
374                 ds_put_cstr(&actions, "outport = ");
375                 json_string_escape(lport->name, &actions);
376                 ds_put_cstr(&actions, "; resubmit;");
377                 pipeline_add(&pc, lport->lswitch, 1, 50,
378                              ds_cstr(&match), ds_cstr(&actions));
379                 ds_destroy(&actions);
380                 ds_destroy(&match);
381             } else if (!strcmp(lport->macs[i], "unknown")) {
382                 ds_put_cstr(&unknown_actions, "outport = ");
383                 json_string_escape(lport->name, &unknown_actions);
384                 ds_put_cstr(&unknown_actions, "; resubmit; ");
385             } else {
386                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
387
388                 VLOG_INFO_RL(&rl, "%s: invalid syntax '%s' in macs column",
389                              lport->name, lport->macs[i]);
390             }
391         }
392     }
393
394     /* Table 1: Destination lookup for unknown MACs (priority 0). */
395     if (unknown_actions.length) {
396         ds_chomp(&unknown_actions, ' ');
397         pipeline_add(&pc, lport->lswitch, 1, 0, "1",
398                      ds_cstr(&unknown_actions));
399     }
400     ds_destroy(&unknown_actions);
401
402     /* Table 2: ACLs. */
403     const struct nbrec_acl *acl;
404     NBREC_ACL_FOR_EACH (acl, ctx->ovnnb_idl) {
405         const char *action;
406
407         action = (!strcmp(acl->action, "allow") ||
408                   !strcmp(acl->action, "allow-related"))
409                       ? "resubmit;" : "drop;";
410         pipeline_add(&pc, acl->lswitch, 2, acl->priority, acl->match, action);
411     }
412     NBREC_LOGICAL_SWITCH_FOR_EACH (lswitch, ctx->ovnnb_idl) {
413         pipeline_add(&pc, lswitch, 2, 0, "1", "resubmit;");
414     }
415
416     /* Table 3: Egress port security. */
417     NBREC_LOGICAL_PORT_FOR_EACH (lport, ctx->ovnnb_idl) {
418         struct ds match, actions;
419
420         ds_init(&match);
421         ds_put_cstr(&match, "outport == ");
422         json_string_escape(lport->name, &match);
423         build_port_security("eth.dst",
424                             lport->port_security, lport->n_port_security,
425                             &match);
426
427         ds_init(&actions);
428         ds_put_cstr(&actions, "output(");
429         json_string_escape(lport->name, &actions);
430         ds_put_cstr(&actions, ");");
431
432         pipeline_add(&pc, lport->lswitch, 3, 50,
433                      ds_cstr(&match), ds_cstr(&actions));
434
435         ds_destroy(&actions);
436         ds_destroy(&match);
437     }
438
439     /* Delete any existing Pipeline rows that were not re-generated.  */
440     struct pipeline_hash_node *hash_node, *next_hash_node;
441     HMAP_FOR_EACH_SAFE (hash_node, next_hash_node, node, &pc.pipeline_hmap) {
442         hmap_remove(&pc.pipeline_hmap, &hash_node->node);
443         sbrec_pipeline_delete(hash_node->pipeline);
444         free(hash_node);
445     }
446     hmap_destroy(&pc.pipeline_hmap);
447 }
448 \f
449 static bool
450 parents_equal(const struct sbrec_bindings *binding,
451               const struct nbrec_logical_port *lport)
452 {
453     if (!!binding->parent_port != !!lport->parent_name) {
454         /* One is set and the other is not. */
455         return false;
456     }
457
458     if (binding->parent_port) {
459         /* Both are set. */
460         return strcmp(binding->parent_port, lport->parent_name) ? false : true;
461     }
462
463     /* Both are NULL. */
464     return true;
465 }
466
467 static bool
468 tags_equal(const struct sbrec_bindings *binding,
469            const struct nbrec_logical_port *lport)
470 {
471     if (binding->n_tag != lport->n_tag) {
472         return false;
473     }
474
475     return binding->n_tag ? (binding->tag[0] == lport->tag[0]) : true;
476 }
477
478 /*
479  * When a change has occurred in the OVN_Northbound database, we go through and
480  * make sure that the contents of the Bindings table in the OVN_Southbound
481  * database are up to date with the logical ports defined in the
482  * OVN_Northbound database.
483  */
484 static void
485 set_bindings(struct northd_context *ctx)
486 {
487     struct hmap bindings_hmap;
488     const struct sbrec_bindings *binding;
489     const struct nbrec_logical_port *lport;
490
491     struct binding_hash_node {
492         struct hmap_node node;
493         const struct sbrec_bindings *binding;
494     } *hash_node, *hash_node_next;
495
496     /*
497      * We will need to look up a binding for every logical port.  We don't want
498      * to have to do an O(n) search for every binding, so start out by hashing
499      * them on the logical port.
500      *
501      * As we go through every logical port, we will update the binding if it
502      * exists or create one otherwise.  When the update is done, we'll remove it
503      * from the hashmap.  At the end, any bindings left in the hashmap are for
504      * logical ports that have been deleted.
505      */
506     hmap_init(&bindings_hmap);
507
508     SBREC_BINDINGS_FOR_EACH(binding, ctx->ovnsb_idl) {
509         hash_node = xzalloc(sizeof *hash_node);
510         hash_node->binding = binding;
511         hmap_insert(&bindings_hmap, &hash_node->node,
512                 hash_string(binding->logical_port, 0));
513     }
514
515     NBREC_LOGICAL_PORT_FOR_EACH(lport, ctx->ovnnb_idl) {
516         binding = NULL;
517         HMAP_FOR_EACH_WITH_HASH(hash_node, node,
518                 hash_string(lport->name, 0), &bindings_hmap) {
519             if (!strcmp(lport->name, hash_node->binding->logical_port)) {
520                 binding = hash_node->binding;
521                 break;
522             }
523         }
524
525         if (binding) {
526             /* We found an existing binding for this logical port.  Update its
527              * contents. */
528
529             hmap_remove(&bindings_hmap, &hash_node->node);
530             free(hash_node);
531             hash_node = NULL;
532
533             if (!macs_equal(binding->mac, binding->n_mac,
534                         lport->macs, lport->n_macs)) {
535                 sbrec_bindings_set_mac(binding,
536                         (const char **) lport->macs, lport->n_macs);
537             }
538             if (!parents_equal(binding, lport)) {
539                 sbrec_bindings_set_parent_port(binding, lport->parent_name);
540             }
541             if (!tags_equal(binding, lport)) {
542                 sbrec_bindings_set_tag(binding, lport->tag, lport->n_tag);
543             }
544         } else {
545             /* There is no binding for this logical port, so create one. */
546
547             binding = sbrec_bindings_insert(ctx->ovnsb_txn);
548             sbrec_bindings_set_logical_port(binding, lport->name);
549             sbrec_bindings_set_mac(binding,
550                     (const char **) lport->macs, lport->n_macs);
551             if (lport->parent_name && lport->n_tag > 0) {
552                 sbrec_bindings_set_parent_port(binding, lport->parent_name);
553                 sbrec_bindings_set_tag(binding, lport->tag, lport->n_tag);
554             }
555         }
556     }
557
558     HMAP_FOR_EACH_SAFE(hash_node, hash_node_next, node, &bindings_hmap) {
559         hmap_remove(&bindings_hmap, &hash_node->node);
560         sbrec_bindings_delete(hash_node->binding);
561         free(hash_node);
562     }
563     hmap_destroy(&bindings_hmap);
564 }
565
566 static void
567 ovnnb_db_changed(struct northd_context *ctx)
568 {
569     VLOG_DBG("ovn-nb db contents have changed.");
570
571     set_bindings(ctx);
572     build_pipeline(ctx);
573 }
574
575 /*
576  * The only change we get notified about is if the 'chassis' column of the
577  * 'Bindings' table changes.  When this column is not empty, it means we need to
578  * set the corresponding logical port as 'up' in the northbound DB.
579  */
580 static void
581 ovnsb_db_changed(struct northd_context *ctx)
582 {
583     struct hmap lports_hmap;
584     const struct sbrec_bindings *binding;
585     const struct nbrec_logical_port *lport;
586
587     struct lport_hash_node {
588         struct hmap_node node;
589         const struct nbrec_logical_port *lport;
590     } *hash_node, *hash_node_next;
591
592     VLOG_DBG("Recalculating port up states for ovn-nb db.");
593
594     hmap_init(&lports_hmap);
595
596     NBREC_LOGICAL_PORT_FOR_EACH(lport, ctx->ovnnb_idl) {
597         hash_node = xzalloc(sizeof *hash_node);
598         hash_node->lport = lport;
599         hmap_insert(&lports_hmap, &hash_node->node,
600                 hash_string(lport->name, 0));
601     }
602
603     SBREC_BINDINGS_FOR_EACH(binding, ctx->ovnsb_idl) {
604         lport = NULL;
605         HMAP_FOR_EACH_WITH_HASH(hash_node, node,
606                 hash_string(binding->logical_port, 0), &lports_hmap) {
607             if (!strcmp(binding->logical_port, hash_node->lport->name)) {
608                 lport = hash_node->lport;
609                 break;
610             }
611         }
612
613         if (!lport) {
614             /* The logical port doesn't exist for this binding.  This can
615              * happen under normal circumstances when ovn-northd hasn't gotten
616              * around to pruning the Binding yet. */
617             continue;
618         }
619
620         if (*binding->chassis && (!lport->up || !*lport->up)) {
621             bool up = true;
622             nbrec_logical_port_set_up(lport, &up, 1);
623         } else if (!*binding->chassis && (!lport->up || *lport->up)) {
624             bool up = false;
625             nbrec_logical_port_set_up(lport, &up, 1);
626         }
627     }
628
629     HMAP_FOR_EACH_SAFE(hash_node, hash_node_next, node, &lports_hmap) {
630         hmap_remove(&lports_hmap, &hash_node->node);
631         free(hash_node);
632     }
633     hmap_destroy(&lports_hmap);
634 }
635 \f
636 static const char *
637 default_db(void)
638 {
639     static char *def;
640     if (!def) {
641         def = xasprintf("unix:%s/db.sock", ovs_rundir());
642     }
643     return def;
644 }
645
646 static void
647 parse_options(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
648 {
649     enum {
650         DAEMON_OPTION_ENUMS,
651         VLOG_OPTION_ENUMS,
652     };
653     static const struct option long_options[] = {
654         {"ovnsb-db", required_argument, NULL, 'd'},
655         {"ovnnb-db", required_argument, NULL, 'D'},
656         {"help", no_argument, NULL, 'h'},
657         {"options", no_argument, NULL, 'o'},
658         {"version", no_argument, NULL, 'V'},
659         DAEMON_LONG_OPTIONS,
660         VLOG_LONG_OPTIONS,
661         STREAM_SSL_LONG_OPTIONS,
662         {NULL, 0, NULL, 0},
663     };
664     char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
665
666     for (;;) {
667         int c;
668
669         c = getopt_long(argc, argv, short_options, long_options, NULL);
670         if (c == -1) {
671             break;
672         }
673
674         switch (c) {
675         DAEMON_OPTION_HANDLERS;
676         VLOG_OPTION_HANDLERS;
677         STREAM_SSL_OPTION_HANDLERS;
678
679         case 'd':
680             ovnsb_db = optarg;
681             break;
682
683         case 'D':
684             ovnnb_db = optarg;
685             break;
686
687         case 'h':
688             usage();
689             exit(EXIT_SUCCESS);
690
691         case 'o':
692             ovs_cmdl_print_options(long_options);
693             exit(EXIT_SUCCESS);
694
695         case 'V':
696             ovs_print_version(0, 0);
697             exit(EXIT_SUCCESS);
698
699         default:
700             break;
701         }
702     }
703
704     if (!ovnsb_db) {
705         ovnsb_db = default_db();
706     }
707
708     if (!ovnnb_db) {
709         ovnnb_db = default_db();
710     }
711
712     free(short_options);
713 }
714
715 int
716 main(int argc, char *argv[])
717 {
718     extern struct vlog_module VLM_reconnect;
719     struct ovsdb_idl *ovnnb_idl, *ovnsb_idl;
720     unsigned int ovnnb_seqno, ovn_seqno;
721     int res = EXIT_SUCCESS;
722     struct northd_context ctx = {
723         .ovnsb_txn = NULL,
724     };
725     bool ovnnb_changes_pending = false;
726     bool ovn_changes_pending = false;
727
728     fatal_ignore_sigpipe();
729     set_program_name(argv[0]);
730     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
731     vlog_set_levels(&VLM_reconnect, VLF_ANY_DESTINATION, VLL_WARN);
732     parse_options(argc, argv);
733
734     daemonize();
735
736     nbrec_init();
737     sbrec_init();
738
739     /* We want to detect all changes to the ovn-nb db. */
740     ctx.ovnnb_idl = ovnnb_idl = ovsdb_idl_create(ovnnb_db,
741             &nbrec_idl_class, true, true);
742
743     /* There is only a small subset of changes to the ovn-sb db that ovn-northd
744      * has to care about, so we'll enable monitoring those directly. */
745     ctx.ovnsb_idl = ovnsb_idl = ovsdb_idl_create(ovnsb_db,
746             &sbrec_idl_class, false, true);
747     ovsdb_idl_add_table(ovnsb_idl, &sbrec_table_bindings);
748     ovsdb_idl_add_column(ovnsb_idl, &sbrec_bindings_col_logical_port);
749     ovsdb_idl_add_column(ovnsb_idl, &sbrec_bindings_col_chassis);
750     ovsdb_idl_add_column(ovnsb_idl, &sbrec_bindings_col_mac);
751     ovsdb_idl_add_column(ovnsb_idl, &sbrec_bindings_col_tag);
752     ovsdb_idl_add_column(ovnsb_idl, &sbrec_bindings_col_parent_port);
753     ovsdb_idl_add_column(ovnsb_idl, &sbrec_pipeline_col_logical_datapath);
754     ovsdb_idl_omit_alert(ovnsb_idl, &sbrec_pipeline_col_logical_datapath);
755     ovsdb_idl_add_column(ovnsb_idl, &sbrec_pipeline_col_table_id);
756     ovsdb_idl_omit_alert(ovnsb_idl, &sbrec_pipeline_col_table_id);
757     ovsdb_idl_add_column(ovnsb_idl, &sbrec_pipeline_col_priority);
758     ovsdb_idl_omit_alert(ovnsb_idl, &sbrec_pipeline_col_priority);
759     ovsdb_idl_add_column(ovnsb_idl, &sbrec_pipeline_col_match);
760     ovsdb_idl_omit_alert(ovnsb_idl, &sbrec_pipeline_col_match);
761     ovsdb_idl_add_column(ovnsb_idl, &sbrec_pipeline_col_actions);
762     ovsdb_idl_omit_alert(ovnsb_idl, &sbrec_pipeline_col_actions);
763
764     /*
765      * The loop here just runs the IDL in a loop waiting for the seqno to
766      * change, which indicates that the contents of the db have changed.
767      *
768      * If the contents of the ovn-nb db change, the mappings to the ovn-sb
769      * db must be recalculated.
770      *
771      * If the contents of the ovn-sb db change, it means the 'up' state of
772      * a port may have changed, as that's the only type of change ovn-northd is
773      * watching for.
774      */
775
776     ovnnb_seqno = ovsdb_idl_get_seqno(ovnnb_idl);
777     ovn_seqno = ovsdb_idl_get_seqno(ovnsb_idl);
778     for (;;) {
779         ovsdb_idl_run(ovnnb_idl);
780         ovsdb_idl_run(ovnsb_idl);
781
782         if (!ovsdb_idl_is_alive(ovnnb_idl)) {
783             int retval = ovsdb_idl_get_last_error(ovnnb_idl);
784             VLOG_ERR("%s: database connection failed (%s)",
785                     ovnnb_db, ovs_retval_to_string(retval));
786             res = EXIT_FAILURE;
787             break;
788         }
789
790         if (!ovsdb_idl_is_alive(ovnsb_idl)) {
791             int retval = ovsdb_idl_get_last_error(ovnsb_idl);
792             VLOG_ERR("%s: database connection failed (%s)",
793                     ovnsb_db, ovs_retval_to_string(retval));
794             res = EXIT_FAILURE;
795             break;
796         }
797
798         if (ovnnb_seqno != ovsdb_idl_get_seqno(ovnnb_idl)) {
799             ovnnb_seqno = ovsdb_idl_get_seqno(ovnnb_idl);
800             ovnnb_changes_pending = true;
801         }
802
803         if (ovn_seqno != ovsdb_idl_get_seqno(ovnsb_idl)) {
804             ovn_seqno = ovsdb_idl_get_seqno(ovnsb_idl);
805             ovn_changes_pending = true;
806         }
807
808         /*
809          * If there are any pending changes, we delay recalculating the
810          * necessary updates until after an existing transaction finishes.
811          * This avoids the possibility of rapid updates causing ovn-northd to
812          * never be able to successfully make the corresponding updates to the
813          * other db.  Instead, pending changes are batched up until the next
814          * time we get a chance to calculate the new state and apply it.
815          */
816
817         if (ovnnb_changes_pending && !ctx.ovnsb_txn) {
818             /*
819              * The OVN-nb db contents have changed, so create a transaction for
820              * updating the OVN-sb DB.
821              */
822             ctx.ovnsb_txn = ovsdb_idl_txn_create(ctx.ovnsb_idl);
823             ovsdb_idl_txn_add_comment(ctx.ovnsb_txn,
824                                       "ovn-northd: northbound db changed");
825             ovnnb_db_changed(&ctx);
826             ovnnb_changes_pending = false;
827         }
828
829         if (ovn_changes_pending && !ctx.ovnnb_txn) {
830             /*
831              * The OVN-sb db contents have changed, so create a transaction for
832              * updating the northbound DB.
833              */
834             ctx.ovnnb_txn = ovsdb_idl_txn_create(ctx.ovnnb_idl);
835             ovsdb_idl_txn_add_comment(ctx.ovnnb_txn,
836                                       "ovn-northd: southbound db changed");
837             ovnsb_db_changed(&ctx);
838             ovn_changes_pending = false;
839         }
840
841         if (ctx.ovnnb_txn) {
842             enum ovsdb_idl_txn_status txn_status;
843             txn_status = ovsdb_idl_txn_commit(ctx.ovnnb_txn);
844             switch (txn_status) {
845             case TXN_UNCOMMITTED:
846             case TXN_INCOMPLETE:
847                 /* Come back around and try to commit this transaction again */
848                 break;
849             case TXN_ABORTED:
850             case TXN_TRY_AGAIN:
851             case TXN_NOT_LOCKED:
852             case TXN_ERROR:
853                 /* Something went wrong, so try creating a new transaction. */
854                 ovn_changes_pending = true;
855             case TXN_UNCHANGED:
856             case TXN_SUCCESS:
857                 ovsdb_idl_txn_destroy(ctx.ovnnb_txn);
858                 ctx.ovnnb_txn = NULL;
859             }
860         }
861
862         if (ctx.ovnsb_txn) {
863             enum ovsdb_idl_txn_status txn_status;
864             txn_status = ovsdb_idl_txn_commit(ctx.ovnsb_txn);
865             switch (txn_status) {
866             case TXN_UNCOMMITTED:
867             case TXN_INCOMPLETE:
868                 /* Come back around and try to commit this transaction again */
869                 break;
870             case TXN_ABORTED:
871             case TXN_TRY_AGAIN:
872             case TXN_NOT_LOCKED:
873             case TXN_ERROR:
874                 /* Something went wrong, so try creating a new transaction. */
875                 ovnnb_changes_pending = true;
876             case TXN_UNCHANGED:
877             case TXN_SUCCESS:
878                 ovsdb_idl_txn_destroy(ctx.ovnsb_txn);
879                 ctx.ovnsb_txn = NULL;
880             }
881         }
882
883         if (ovnnb_seqno == ovsdb_idl_get_seqno(ovnnb_idl) &&
884                 ovn_seqno == ovsdb_idl_get_seqno(ovnsb_idl)) {
885             ovsdb_idl_wait(ovnnb_idl);
886             ovsdb_idl_wait(ovnsb_idl);
887             if (ctx.ovnnb_txn) {
888                 ovsdb_idl_txn_wait(ctx.ovnnb_txn);
889             }
890             if (ctx.ovnsb_txn) {
891                 ovsdb_idl_txn_wait(ctx.ovnsb_txn);
892             }
893             poll_block();
894         }
895     }
896
897     ovsdb_idl_destroy(ovnsb_idl);
898     ovsdb_idl_destroy(ovnnb_idl);
899
900     exit(res);
901 }