json: Move from lib to include/openvswitch.
[cascardo/ovs.git] / ovn / controller / patch.c
1 /* Copyright (c) 2015, 2016 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "patch.h"
19
20 #include "hash.h"
21 #include "lflow.h"
22 #include "lib/vswitch-idl.h"
23 #include "lport.h"
24 #include "openvswitch/hmap.h"
25 #include "openvswitch/vlog.h"
26 #include "ovn-controller.h"
27
28 VLOG_DEFINE_THIS_MODULE(patch);
29
30 static char *
31 patch_port_name(const char *src, const char *dst)
32 {
33     return xasprintf("patch-%s-to-%s", src, dst);
34 }
35
36 /* Return true if 'port' is a patch port with the specified 'peer'. */
37 static bool
38 match_patch_port(const struct ovsrec_port *port, const char *peer)
39 {
40     for (size_t i = 0; i < port->n_interfaces; i++) {
41         struct ovsrec_interface *iface = port->interfaces[i];
42         if (strcmp(iface->type, "patch")) {
43             continue;
44         }
45         const char *iface_peer = smap_get(&iface->options, "peer");
46         if (peer && !strcmp(iface_peer, peer)) {
47             return true;
48         }
49     }
50     return false;
51 }
52
53 /* Creates a patch port in bridge 'src' named 'src_name', whose peer is
54  * 'dst_name' in bridge 'dst'.  Initializes the patch port's external-ids:'key'
55  * to 'key'.
56  *
57  * If such a patch port already exists, removes it from 'existing_ports'. */
58 static void
59 create_patch_port(struct controller_ctx *ctx,
60                   const char *key, const char *value,
61                   const struct ovsrec_bridge *src, const char *src_name,
62                   const struct ovsrec_bridge *dst, const char *dst_name,
63                   struct shash *existing_ports)
64 {
65     for (size_t i = 0; i < src->n_ports; i++) {
66         if (match_patch_port(src->ports[i], dst_name)) {
67             /* Patch port already exists on 'src'. */
68             shash_find_and_delete(existing_ports, src->ports[i]->name);
69             return;
70         }
71     }
72
73     ovsdb_idl_txn_add_comment(ctx->ovs_idl_txn,
74             "ovn-controller: creating patch port '%s' from '%s' to '%s'",
75             src_name, src->name, dst->name);
76
77     struct ovsrec_interface *iface;
78     iface = ovsrec_interface_insert(ctx->ovs_idl_txn);
79     ovsrec_interface_set_name(iface, src_name);
80     ovsrec_interface_set_type(iface, "patch");
81     const struct smap options = SMAP_CONST1(&options, "peer", dst_name);
82     ovsrec_interface_set_options(iface, &options);
83
84     struct ovsrec_port *port;
85     port = ovsrec_port_insert(ctx->ovs_idl_txn);
86     ovsrec_port_set_name(port, src_name);
87     ovsrec_port_set_interfaces(port, &iface, 1);
88     const struct smap ids = SMAP_CONST1(&ids, key, value);
89     ovsrec_port_set_external_ids(port, &ids);
90
91     struct ovsrec_port **ports;
92     ports = xmalloc(sizeof *ports * (src->n_ports + 1));
93     memcpy(ports, src->ports, sizeof *ports * src->n_ports);
94     ports[src->n_ports] = port;
95     ovsrec_bridge_verify_ports(src);
96     ovsrec_bridge_set_ports(src, ports, src->n_ports + 1);
97
98     lport_index_reset();
99     mcgroup_index_reset();
100     lflow_reset_processing();
101     free(ports);
102 }
103
104 static void
105 remove_port(struct controller_ctx *ctx,
106             const struct ovsrec_port *port)
107 {
108     const struct ovsrec_bridge *bridge;
109
110     /* We know the port we want to delete, but we have to find the bridge its
111      * on to do so.  Note this only runs on a config change that should be
112      * pretty rare. */
113     OVSREC_BRIDGE_FOR_EACH (bridge, ctx->ovs_idl) {
114         size_t i;
115         for (i = 0; i < bridge->n_ports; i++) {
116             if (bridge->ports[i] != port) {
117                 continue;
118             }
119             struct ovsrec_port **new_ports;
120             new_ports = xmemdup(bridge->ports,
121                     sizeof *new_ports * (bridge->n_ports - 1));
122             if (i != bridge->n_ports - 1) {
123                 /* Removed port was not last */
124                 new_ports[i] = bridge->ports[bridge->n_ports - 1];
125             }
126             ovsrec_bridge_verify_ports(bridge);
127             ovsrec_bridge_set_ports(bridge, new_ports, bridge->n_ports - 1);
128             free(new_ports);
129             ovsrec_port_delete(port);
130             return;
131         }
132     }
133     lport_index_reset();
134     mcgroup_index_reset();
135     lflow_reset_processing();
136 }
137
138 /* Obtains external-ids:ovn-bridge-mappings from OVSDB and adds patch ports for
139  * the local bridge mappings.  Removes any patch ports for bridge mappings that
140  * already existed from 'existing_ports'. */
141 static void
142 add_bridge_mappings(struct controller_ctx *ctx,
143                     const struct ovsrec_bridge *br_int,
144                     struct shash *existing_ports,
145                     struct hmap *local_datapaths,
146                     const char *chassis_id)
147 {
148     /* Get ovn-bridge-mappings. */
149     const char *mappings_cfg = "";
150     const struct ovsrec_open_vswitch *cfg;
151     cfg = ovsrec_open_vswitch_first(ctx->ovs_idl);
152     if (cfg) {
153         mappings_cfg = smap_get(&cfg->external_ids, "ovn-bridge-mappings");
154         if (!mappings_cfg) {
155             mappings_cfg = "";
156         }
157     }
158
159     /* Parse bridge mappings. */
160     struct shash bridge_mappings = SHASH_INITIALIZER(&bridge_mappings);
161     char *cur, *next, *start;
162     next = start = xstrdup(mappings_cfg);
163     while ((cur = strsep(&next, ",")) && *cur) {
164         char *network, *bridge = cur;
165         const struct ovsrec_bridge *ovs_bridge;
166
167         network = strsep(&bridge, ":");
168         if (!bridge || !*network || !*bridge) {
169             VLOG_ERR("Invalid ovn-bridge-mappings configuration: '%s'",
170                     mappings_cfg);
171             break;
172         }
173
174         ovs_bridge = get_bridge(ctx->ovs_idl, bridge);
175         if (!ovs_bridge) {
176             VLOG_WARN("Bridge '%s' not found for network '%s'",
177                     bridge, network);
178             continue;
179         }
180
181         shash_add(&bridge_mappings, network, ovs_bridge);
182     }
183     free(start);
184
185     const struct sbrec_port_binding *binding;
186     SBREC_PORT_BINDING_FOR_EACH (binding, ctx->ovnsb_idl) {
187         const char *patch_port_id;
188         if (!strcmp(binding->type, "localnet")) {
189             struct local_datapath *ld
190                 = get_local_datapath(local_datapaths,
191                                      binding->datapath->tunnel_key);
192             if (!ld) {
193                 /* This localnet port is on a datapath with no
194                  * logical ports bound to this chassis, so there's no need
195                  * to create patch ports for it. */
196                 continue;
197             }
198
199             /* Under incremental processing, it is possible to re-enter the
200              * following block with a logical port that has already been
201              * recorded in binding->logical_port.  Rather than emit spurious
202              * warnings, add a check to see if the logical port name has
203              * actually changed. */
204
205             if (ld->localnet_port && strcmp(ld->localnet_port->logical_port,
206                                             binding->logical_port)) {
207                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
208                 VLOG_WARN_RL(&rl, "localnet port '%s' already set for datapath "
209                              "'%"PRId64"', skipping the new port '%s'.",
210                              ld->localnet_port->logical_port,
211                              binding->datapath->tunnel_key,
212                              binding->logical_port);
213                 continue;
214             }
215             ld->localnet_port = binding;
216             patch_port_id = "ovn-localnet-port";
217         } else if (!strcmp(binding->type, "l2gateway")) {
218             if (!binding->chassis
219                 || strcmp(chassis_id, binding->chassis->name)) {
220                 /* This L2 gateway port is not bound to this chassis,
221                  * so we should not create any patch ports for it. */
222                 continue;
223             }
224             patch_port_id = "ovn-l2gateway-port";
225         } else {
226             /* not a localnet or L2 gateway port. */
227             continue;
228         }
229
230         const char *network = smap_get(&binding->options, "network_name");
231         if (!network) {
232             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
233             VLOG_ERR_RL(&rl, "%s port '%s' has no network name.",
234                          binding->type, binding->logical_port);
235             continue;
236         }
237         struct ovsrec_bridge *br_ln = shash_find_data(&bridge_mappings, network);
238         if (!br_ln) {
239             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
240             VLOG_ERR_RL(&rl, "bridge not found for %s port '%s' "
241                     "with network name '%s'",
242                     binding->type, binding->logical_port, network);
243             continue;
244         }
245
246         char *name1 = patch_port_name(br_int->name, binding->logical_port);
247         char *name2 = patch_port_name(binding->logical_port, br_int->name);
248         create_patch_port(ctx, patch_port_id, binding->logical_port,
249                           br_int, name1, br_ln, name2, existing_ports);
250         create_patch_port(ctx, patch_port_id, binding->logical_port,
251                           br_ln, name2, br_int, name1, existing_ports);
252         free(name1);
253         free(name2);
254     }
255
256     shash_destroy(&bridge_mappings);
257 }
258
259 static void
260 add_patched_datapath(struct hmap *patched_datapaths,
261                      const struct sbrec_port_binding *binding_rec, bool local)
262 {
263     struct patched_datapath *pd = get_patched_datapath(patched_datapaths,
264                                        binding_rec->datapath->tunnel_key);
265     if (pd) {
266         /* If the patched datapath is referenced by a logical patch port it is
267          * not stale, by definition, so set 'stale' to false */
268         pd->stale = false;
269         return;
270     }
271
272     pd = xzalloc(sizeof *pd);
273     pd->local = local;
274     pd->key = xasprintf(UUID_FMT,
275                         UUID_ARGS(&binding_rec->datapath->header_.uuid));
276     /* stale is set to false. */
277     hmap_insert(patched_datapaths, &pd->hmap_node,
278                 binding_rec->datapath->tunnel_key);
279 }
280
281 static void
282 add_logical_patch_ports_preprocess(struct hmap *patched_datapaths)
283 {
284     /* Mark all patched datapaths as stale for later cleanup by
285      * add_logical_patch_ports_postprocess(). */
286     struct patched_datapath *pd;
287     HMAP_FOR_EACH (pd, hmap_node, patched_datapaths) {
288         pd->stale = true;
289     }
290 }
291
292 /* This function should cleanup stale patched datapaths and any memory
293  * allocated for fields within a stale patched datapath. */
294 static void
295 add_logical_patch_ports_postprocess(struct hmap *patched_datapaths)
296 {
297     /* Clean up stale patched datapaths. */
298     struct patched_datapath *pd_cur_node, *pd_next_node;
299     HMAP_FOR_EACH_SAFE (pd_cur_node, pd_next_node, hmap_node,
300                         patched_datapaths) {
301         if (pd_cur_node->stale == true) {
302             hmap_remove(patched_datapaths, &pd_cur_node->hmap_node);
303             free(pd_cur_node->key);
304             free(pd_cur_node);
305         }
306     }
307 }
308
309 /* Add one OVS patch port for each OVN logical patch port.
310  *
311  * This is suboptimal for several reasons.  First, it creates an OVS port for
312  * every OVN logical patch port, not just for the ones that are actually useful
313  * on this hypervisor.  Second, it's wasteful to create an OVS patch port per
314  * OVN logical patch port, when really there's no benefit to them beyond a way
315  * to identify how a packet ingressed into a logical datapath.
316  *
317  * There are two obvious ways to improve the situation here, by modifying
318  * OVS:
319  *
320  *     1. Add a way to configure in OVS which fields are preserved on a hop
321  *        across an OVS patch port.  If MFF_LOG_DATAPATH and MFF_LOG_INPORT
322  *        were preserved, then only a single pair of OVS patch ports would be
323  *        required regardless of the number of OVN logical patch ports.
324  *
325  *     2. Add a new OpenFlow extension action modeled on "resubmit" that also
326  *        saves and restores the packet data and metadata (the inability to do
327  *        this is the only reason that "resubmit" can't be used already).  Or
328  *        add OpenFlow extension actions to otherwise save and restore packet
329  *        data and metadata.
330  */
331 static void
332 add_logical_patch_ports(struct controller_ctx *ctx,
333                         const struct ovsrec_bridge *br_int,
334                         const char *local_chassis_id,
335                         struct shash *existing_ports,
336                         struct hmap *patched_datapaths)
337 {
338     const struct sbrec_chassis *chassis_rec;
339     chassis_rec = get_chassis(ctx->ovnsb_idl, local_chassis_id);
340     if (!chassis_rec) {
341         return;
342     }
343
344     add_logical_patch_ports_preprocess(patched_datapaths);
345
346     const struct sbrec_port_binding *binding;
347     SBREC_PORT_BINDING_FOR_EACH (binding, ctx->ovnsb_idl) {
348         bool local_port = false;
349         if (!strcmp(binding->type, "gateway")) {
350             const char *chassis = smap_get(&binding->options,
351                                            "gateway-chassis");
352             if (chassis && !strcmp(local_chassis_id, chassis)) {
353                 local_port = true;
354             }
355         }
356
357         if (!strcmp(binding->type, "patch") || local_port) {
358             const char *local = binding->logical_port;
359             const char *peer = smap_get(&binding->options, "peer");
360             if (!peer) {
361                 continue;
362             }
363
364             char *src_name = patch_port_name(local, peer);
365             char *dst_name = patch_port_name(peer, local);
366             create_patch_port(ctx, "ovn-logical-patch-port", local,
367                               br_int, src_name, br_int, dst_name,
368                               existing_ports);
369             free(dst_name);
370             free(src_name);
371             add_patched_datapath(patched_datapaths, binding, local_port);
372             if (local_port) {
373                 if (binding->chassis != chassis_rec && ctx->ovnsb_idl_txn) {
374                     sbrec_port_binding_set_chassis(binding, chassis_rec);
375                 }
376             }
377         }
378     }
379     add_logical_patch_ports_postprocess(patched_datapaths);
380 }
381
382 void
383 patch_run(struct controller_ctx *ctx, const struct ovsrec_bridge *br_int,
384           const char *chassis_id, struct hmap *local_datapaths,
385           struct hmap *patched_datapaths)
386 {
387     if (!ctx->ovs_idl_txn) {
388         return;
389     }
390
391     /* Figure out what patch ports already exist. */
392     struct shash existing_ports = SHASH_INITIALIZER(&existing_ports);
393     const struct ovsrec_port *port;
394     OVSREC_PORT_FOR_EACH (port, ctx->ovs_idl) {
395         if (smap_get(&port->external_ids, "ovn-localnet-port")
396             || smap_get(&port->external_ids, "ovn-l2gateway-port")
397             || smap_get(&port->external_ids, "ovn-logical-patch-port")) {
398             shash_add(&existing_ports, port->name, port);
399         }
400     }
401
402     /* Create in the database any patch ports that should exist.  Remove from
403      * 'existing_ports' any patch ports that do exist in the database and
404      * should be there. */
405     add_bridge_mappings(ctx, br_int, &existing_ports, local_datapaths, chassis_id);
406     add_logical_patch_ports(ctx, br_int, chassis_id, &existing_ports,
407                             patched_datapaths);
408
409     /* Now 'existing_ports' only still contains patch ports that exist in the
410      * database but shouldn't.  Delete them from the database. */
411     struct shash_node *port_node, *port_next_node;
412     SHASH_FOR_EACH_SAFE (port_node, port_next_node, &existing_ports) {
413         struct ovsrec_port *port = port_node->data;
414         shash_delete(&existing_ports, port_node);
415         remove_port(ctx, port);
416     }
417     shash_destroy(&existing_ports);
418 }