a89d9de8edc4cfca11ed2e3d750b94a815a6f6e3
[groupbasedpolicy.git] / renderers / ofoverlay / src / main / java / org / opendaylight / groupbasedpolicy / renderer / ofoverlay / flow / ExternalMapper.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow;
10
11 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.addNxRegMatch;
12 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.applyActionIns;
13 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.instructions;
14 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxOutputRegAction;
15
16 import java.math.BigInteger;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20
21 import org.opendaylight.groupbasedpolicy.dto.IndexedTenant;
22 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext;
23 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfWriter;
24 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.RegMatch;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.Segmentation;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg7;
43 import org.apache.commons.net.util.SubnetUtils;
44 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.base.Preconditions;
49
50 /**
51  * Manage the table that assigns source endpoint group, bridge domain, and
52  * router domain to registers to be used by other tables.
53  */
54 public class ExternalMapper extends FlowTable {
55
56     protected static final Logger LOG = LoggerFactory.getLogger(ExternalMapper.class);
57
58     public static short TABLE_ID;
59
60     public ExternalMapper(OfContext ctx, short tableId) {
61         super(ctx);
62         TABLE_ID = tableId;
63     }
64
65     @Override
66     public short getTableId() {
67         return TABLE_ID;
68     }
69
70     @Override
71     public void sync(NodeId nodeId, OfWriter ofWriter) throws Exception {
72
73         if (ctx.getSwitchManager().getExternalPorts(nodeId).isEmpty()) {
74             LOG.trace("No external ports found for node: {}", nodeId);
75             return;
76         }
77         // Default drop all
78         ofWriter.writeFlow(nodeId, TABLE_ID, dropFlow(Integer.valueOf(1), null, TABLE_ID));
79
80         /*
81          * When source address was translated to NAT address, it has to be figured out
82          * whether or not the traffic should be tagged since external interfaces are
83          * considered as trunk ports.
84          *
85          * Subnet to which NAT address belong have to be found so that
86          * corresponding L2FloodDomain can be resolved.
87          *
88          * If the L2FloodDomain contains Segmentation augmentation, a Flow is generated
89          * for applying VLAN tag against traffic with NAT IP as source address.
90          *
91          * Note: NetworkContainment of NAT EndpointL3 point's to subnet of original address.
92          * This is why subnet of NAT IP is resolved here.
93          */
94         Collection<EndpointL3> natL3Endpoints = ctx.getEndpointManager().getL3EndpointsWithNat();
95         if (natL3Endpoints != null) {
96             for (EndpointL3 natL3Ep : natL3Endpoints) {
97                 IpAddress natIpAddress = Preconditions.checkNotNull(natL3Ep.getAugmentation(NatAddress.class),
98                         "NAT address augmentation is missing for NAT endpoint: [{}].", natL3Ep.getKey())
99                     .getNatAddress();
100                 L2FloodDomain natEpl2Fd = resolveL2FloodDomainForIpv4Address(ctx.getTenant(natL3Ep.getTenant()),
101                         Preconditions.checkNotNull(natIpAddress.getIpv4Address(),
102                                 "Endpoint {} does not have IPv4 address in NatAddress augmentation.", natL3Ep.getKey()));
103                 if (natEpl2Fd != null && natEpl2Fd.getAugmentation(Segmentation.class) != null) {
104                     Integer vlanId = natEpl2Fd.getAugmentation(Segmentation.class).getSegmentationId();
105                     ofWriter.writeFlow(nodeId, TABLE_ID, buildPushVlanFlow(natIpAddress.getIpv4Address(), vlanId, 222));
106                 }
107             }
108         }
109
110         /*
111          * Tagging should be also considered when traffic is routed or switched to external domain.
112          *
113          * If the L2FloodDomain of Endpoint contains Segmentation augmentation, a Flow
114          * for applying VLAN tag is generated. The flow matches against REG5 holding
115          * the L2FloodDomain and REG7 holding value of an external interface.
116          */
117         for (Endpoint ep : ctx.getEndpointManager().getEndpointsForNode(nodeId)) {
118             L2FloodDomain l2Fd = ctx.getTenant(ep.getTenant()).resolveL2FloodDomain(ep.getNetworkContainment());
119             Segmentation segmentation = l2Fd.getAugmentation(Segmentation.class);
120             if (segmentation == null) {
121                 continue;
122             }
123             Integer vlanId = segmentation.getSegmentationId();
124             for (Flow flow : buildPushVlanFlow(nodeId, OrdinalFactory.getEndpointFwdCtxOrdinals(ctx, ep).getFdId(),
125                     vlanId, 220)) {
126                 ofWriter.writeFlow(nodeId, TABLE_ID, flow);
127             }
128         }
129
130         /*
131          *  Default Egress flow. Other methods may write to this table to augment egress
132          *  functionality, such as bypassing/utilising the NAT table, or ServiceFunctionChaining
133          */
134         ofWriter.writeFlow(nodeId, TABLE_ID, defaultFlow());
135     }
136
137     static L2FloodDomain resolveL2FloodDomainForIpv4Address(IndexedTenant t, Ipv4Address ipv4Addr) {
138         Preconditions.checkNotNull(ipv4Addr);
139         if (t == null || t.getTenant() == null || t.getTenant().getForwardingContext() == null) {
140             return null;
141         }
142         List<Subnet> subnets = t.getTenant().getForwardingContext().getSubnet();
143         if (subnets != null) {
144             for (Subnet subnet : subnets) {
145                 if (belongsToSubnet(ipv4Addr, subnet.getIpPrefix().getIpv4Prefix())) {
146                     return t.resolveL2FloodDomain(subnet.getParent());
147                 }
148             }
149         }
150         LOG.warn(
151                 "No subnet for IPv4 address {} found in tenant {}!",
152                 ipv4Addr.getValue(), t.getTenant().getId());
153         return null;
154     }
155
156     static boolean belongsToSubnet(Ipv4Address ipv4Address, Ipv4Prefix subnetPrefix) {
157         SubnetUtils su = new SubnetUtils(subnetPrefix.getValue());
158         SubnetInfo si = su.getInfo();
159         return si.isInRange(ipv4Address.getValue());
160     }
161
162     /**
163      * Generates a {@link Flow} for tagging VLAN traffic based on given arguments.
164      *
165      * @param ipv4Address source IPv4 address
166      * @param vlanId ID of VLAN tag to apply
167      * @param priority priority of the flow in the table
168      * @return {@link Flow} matching IPv4 source address, IPv4 ether-type and VLAN not set.
169      */
170     private Flow buildPushVlanFlow(Ipv4Address ipv4Address, Integer vlanId, int priority) {
171         // It is not needed here to match against external interfaces because
172         // we only use NAT when going to external networks.
173         Ipv4Prefix natIp = new Ipv4Prefix(ipv4Address.getValue() + "/32");
174         Match match = new MatchBuilder()
175             .setEthernetMatch(FlowUtils.ethernetMatch(null, null, Long.valueOf(FlowUtils.IPv4)))
176             .setLayer3Match(new Ipv4MatchBuilder().setIpv4Source(natIp).build())
177             .setVlanMatch(FlowUtils.vlanMatch(0, false))
178             .build();
179         List<ActionBuilder> pushVlanActions = new ArrayList<>();
180         pushVlanActions.addAll(FlowUtils.pushVlanActions(vlanId));
181         pushVlanActions.add(new ActionBuilder().setOrder(0).setAction(nxOutputRegAction(NxmNxReg7.class)));
182         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "external_nat_push_vlan", match);
183         return base().setPriority(priority)
184             .setId(flowid)
185             .setMatch(match)
186             .setInstructions(FlowUtils.instructions(applyActionIns(pushVlanActions)))
187             .build();
188     }
189
190     /**
191      * Generates a {@link Flow} for tagging VLAN traffic based on given arguments.
192      *
193      * @param nodeId of {@link Node} from which external interfaces are resolved
194      * @param fdId {@link L2FloodDomain} ordinal to match against
195      * @param vlanId applied to the traffic
196      * @param priority of flow in the table
197      * @return {@link List} of {@link Flow} matching {@link L2FloodDomain} in REG5,
198      * external interfaces of {@link Node} in REG7 and VLAN not set.
199      */
200     private List<Flow> buildPushVlanFlow(NodeId nodeId, int fdId, Integer vlanId, int priority) {
201         List<Flow> flows = new ArrayList<>();
202         for (Long portNum : ctx.getSwitchManager().getExternalPortNumbers(nodeId)) {
203             MatchBuilder mb = new MatchBuilder().setVlanMatch(FlowUtils.vlanMatch(0, false));
204             addNxRegMatch(mb, RegMatch.of(NxmNxReg7.class, BigInteger.valueOf(portNum).longValue()),
205                     RegMatch.of(NxmNxReg5.class, Long.valueOf(fdId)));
206             Match match = mb.build();
207             List<ActionBuilder> pushVlanActions = new ArrayList<>();
208             pushVlanActions.addAll(FlowUtils.pushVlanActions(vlanId));
209             pushVlanActions.add(new ActionBuilder().setOrder(0).setAction(nxOutputRegAction(NxmNxReg7.class)));
210             FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "external_push_vlan", match);
211             flows.add(base().setPriority(priority)
212                 .setId(flowid)
213                 .setMatch(match)
214                 .setInstructions(FlowUtils.instructions(applyActionIns(pushVlanActions)))
215                 .build());
216         }
217         return flows;
218     }
219
220     private Flow defaultFlow() {
221         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "defaultExternalFlow", null);
222         Flow flow = base().setPriority(100)
223             .setId(flowid)
224             .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))))
225             .build();
226         return flow;
227     }
228 }