Bug 3540: Implementation of FlowIds based on match data
[groupbasedpolicy.git] / renderers / ofoverlay / src / main / java / org / opendaylight / groupbasedpolicy / renderer / ofoverlay / flow / DestinationMapper.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 com.google.common.base.Optional;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.HashMultimap;
14 import com.google.common.collect.SetMultimap;
15 import com.google.common.collect.Sets;
16 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.groupbasedpolicy.endpoint.EpKey;
19 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext;
20 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.PolicyManager.FlowMap;
21 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.RegMatch;
22 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.OrdinalFactory.EndpointFwdCtxOrdinals;
23 import org.opendaylight.groupbasedpolicy.resolver.EgKey;
24 import org.opendaylight.groupbasedpolicy.resolver.PolicyInfo;
25 import org.opendaylight.groupbasedpolicy.resolver.TenantUtils;
26 import org.opendaylight.groupbasedpolicy.util.IidFactory;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Prefix;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.Endpoints;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Prefix;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.EndpointLocation.LocationType;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.Tenant;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.L3Context;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.Subnet;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Layer3Match;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg4;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg7;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan;
73 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 import java.math.BigInteger;
78 import java.util.ArrayList;
79 import java.util.Collection;
80 import java.util.Collections;
81 import java.util.HashMap;
82 import java.util.HashSet;
83 import java.util.List;
84 import java.util.Map;
85 import java.util.Map.Entry;
86 import java.util.Objects;
87 import java.util.Set;
88
89 import static com.google.common.base.Preconditions.checkNotNull;
90 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.ARP;
91 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.IPv4;
92 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.IPv6;
93 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.addNxRegMatch;
94 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.applyActionIns;
95 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.createNodePath;
96 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.decNwTtlAction;
97 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.ethernetMatch;
98 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.getOfPortNum;
99 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.gotoTableIns;
100 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.groupAction;
101 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.instructions;
102 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadArpOpAction;
103 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadArpShaAction;
104 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadArpSpaAction;
105 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadRegAction;
106 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadTunIPv4Action;
107 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxLoadTunIdAction;
108 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxMoveArpShaToArpThaAction;
109 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxMoveArpSpaToArpTpaAction;
110 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxMoveEthSrcToEthDstAction;
111 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.outputAction;
112 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.setDlDstAction;
113 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.setDlSrcAction;
114 import static org.opendaylight.groupbasedpolicy.util.DataStoreHelper.readFromDs;
115
116 /**
117  * Manage the table that maps the destination address to the next hop for the
118  * path as well as applies any relevant routing transformations.
119  */
120 public class DestinationMapper extends FlowTable {
121
122     protected static final Logger LOG = LoggerFactory.getLogger(DestinationMapper.class);
123
124     // TODO Li alagalah: Improve UT coverage for this class.
125
126     // TODO Li alagalah: Use EndpointL3 for L3 flows, Endpoint for L2 flows
127     // This ensures we have the appropriate network-containment'
128
129     public static short TABLE_ID;
130     /**
131      * This is the MAC address of the magical router in the sky
132      */
133     public static final MacAddress ROUTER_MAC = new MacAddress("88:f0:31:b5:12:b5");
134     public static final MacAddress MULTICAST_MAC = new MacAddress("01:00:00:00:00:00");
135     public static final Integer BASE_L3_PRIORITY = 100;
136
137     public DestinationMapper(OfContext ctx, short tableId) {
138         super(ctx);
139         this.TABLE_ID = tableId;
140     }
141
142     Map<TenantId, HashSet<Subnet>> subnetsByTenant = new HashMap<TenantId, HashSet<Subnet>>();
143
144     @Override
145     public short getTableId() {
146         return TABLE_ID;
147     }
148
149     @Override
150     public void sync(NodeId nodeId, PolicyInfo policyInfo, FlowMap flowMap) throws Exception {
151
152         TenantId currentTenant = null;
153
154         flowMap.writeFlow(nodeId, TABLE_ID, dropFlow(Integer.valueOf(1), null, TABLE_ID));
155
156         SetMultimap<EpKey, EpKey> visitedEps = HashMultimap.create();
157         Set<EndpointFwdCtxOrdinals> epOrdSet = new HashSet<>();
158
159         for (Endpoint srcEp : ctx.getEndpointManager().getEndpointsForNode(nodeId)) {
160             Set<EndpointGroupId> srcEpgIds = new HashSet<>();
161             if (srcEp.getEndpointGroup() != null)
162                 srcEpgIds.add(srcEp.getEndpointGroup());
163             if (srcEp.getEndpointGroups() != null)
164                 srcEpgIds.addAll(srcEp.getEndpointGroups());
165
166             for (EndpointGroupId epgId : srcEpgIds) {
167                 EgKey epg = new EgKey(srcEp.getTenant(), epgId);
168                 Set<EgKey> peers = Sets.union(Collections.singleton(epg), policyInfo.getPeers(epg));
169                 for (EgKey peer : peers) {
170                     for (Endpoint peerEp : ctx.getEndpointManager().getEndpointsForGroup(peer)) {
171                         currentTenant = peerEp.getTenant();
172                         subnetsByTenant.put(currentTenant, getSubnets(currentTenant));
173                         EpKey srcEpKey = new EpKey(srcEp.getL2Context(), srcEp.getMacAddress());
174                         EpKey peerEpKey = new EpKey(peerEp.getL2Context(), peerEp.getMacAddress());
175
176                         if (visitedEps.get(srcEpKey) != null && visitedEps.get(srcEpKey).contains(peerEpKey)) {
177                             continue;
178                         }
179                         syncEP(flowMap, nodeId, policyInfo, srcEp, peerEp);
180                         visitedEps.put(srcEpKey, peerEpKey);
181
182                         // Process subnets and flood-domains for epPeer
183                         EndpointFwdCtxOrdinals epOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx, policyInfo,
184                                 peerEp);
185                         epOrdSet.add(epOrds);
186                     }
187                 }
188             }
189         }
190
191         for (Entry<TenantId, HashSet<Subnet>> subnetEntry : subnetsByTenant.entrySet()) {
192             if (subnetEntry.getValue() == null) {
193                 LOG.trace("Tenant: {} has empty subnet entry.", subnetEntry.getKey());
194                 continue;
195             }
196             currentTenant = subnetEntry.getKey();
197             for (Subnet sn : subnetEntry.getValue()) {
198                 L3Context l3c = getL3ContextForSubnet(currentTenant, sn);
199                 Flow arpFlow = createRouterArpFlow(currentTenant, nodeId, sn,
200                         OrdinalFactory.getContextOrdinal(currentTenant, l3c.getId()));
201                 if (arpFlow != null) {
202                     flowMap.writeFlow(nodeId, TABLE_ID, arpFlow);
203                 } else {
204                     LOG.debug(
205                             "Gateway ARP flow is not created, because virtual router IP has not been set for subnet {} .",
206                             sn.getIpPrefix().getValue());
207                 }
208             }
209         }
210
211         // Write broadcast flows per flood domain.
212         for (EndpointFwdCtxOrdinals epOrd : epOrdSet) {
213             if (groupExists(nodeId, epOrd.getFdId())) {
214                 flowMap.writeFlow(nodeId, TABLE_ID, createBroadcastFlow(epOrd));
215             }
216         }
217
218         // L3 Prefix Endpoint handling
219         Collection<EndpointL3Prefix> prefixEps = ctx.getEndpointManager().getEndpointsL3PrefixForTenant(currentTenant);
220         if (prefixEps != null) {
221             LOG.trace("DestinationMapper - Processing L3PrefixEndpoints");
222             for (EndpointL3Prefix prefixEp : prefixEps) {
223                 Flow prefixFlow = createL3PrefixFlow(prefixEp, policyInfo, nodeId);
224                 if (prefixFlow != null) {
225                     flowMap.writeFlow(nodeId, TABLE_ID, prefixFlow);
226                     LOG.trace("Wrote L3Prefix flow");
227                 }
228             }
229         }
230
231     }
232
233     // set up next-hop destinations for all the endpoints in the endpoint
234     // group on the node
235
236     private Flow createL3PrefixFlow(EndpointL3Prefix prefixEp, PolicyInfo policyInfo, NodeId nodeId) throws Exception {
237         /*
238          * Priority: 100+lengthprefix
239          * Match: prefix, l3c, "mac address of router" ?
240          * Action:
241          * - set Reg2, Reg3 for L3Ep by L2Ep ?
242          * - if external,
243          * - Reg7: use switch location external port else punt for now
244          * - if internal
245          * - Reg7: grab L2Ep from L3Ep and use its location info
246          * - goto_table: POLENF (will check there for external on EP)
247          */
248
249         ReadOnlyTransaction rTx = ctx.getDataBroker().newReadOnlyTransaction();
250         // TODO Bug #3440 Target: Be - should support for more than first gateway.
251         EndpointL3Gateways l3Gateway = prefixEp.getEndpointL3Gateways().get(0);
252         Optional<EndpointL3> optL3Ep = readFromDs(LogicalDatastoreType.OPERATIONAL,
253                 IidFactory.l3EndpointIid(l3Gateway.getL3Context(), l3Gateway.getIpAddress()), rTx);
254         if (!optL3Ep.isPresent()) {
255             LOG.error("createL3PrefixFlow - L3Endpoint gateway {} for L3Prefix {} not found.", l3Gateway, prefixEp);
256             return null;
257         }
258         EndpointL3 l3Ep = optL3Ep.get();
259         Optional<Endpoint> optL2Ep = readFromDs(LogicalDatastoreType.OPERATIONAL,
260                 IidFactory.endpointIid(l3Ep.getL2Context(), l3Ep.getMacAddress()), rTx);
261         if (!optL2Ep.isPresent()) {
262             LOG.error("createL3PrefixFlow - L2Endpoint for L3Gateway {} not found.", l3Ep);
263             return null;
264         }
265         Endpoint l2Ep = optL2Ep.get();
266         EndpointFwdCtxOrdinals epFwdCtxOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx, policyInfo, l2Ep);
267
268         NetworkDomainId epNetworkContainment = getEPNetworkContainment(l2Ep);
269
270         MacAddress epDestMac = l2Ep.getMacAddress();
271         MacAddress destSubnetGatewayMac = l2Ep.getMacAddress();
272
273         ArrayList<Instruction> l3instructions = new ArrayList<>();
274         List<Action> applyActions = new ArrayList<>();
275         List<Action> l3ApplyActions = new ArrayList<>();
276
277         int order = 0;
278
279         Action setdEPG = nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(epFwdCtxOrds.getEpgId()));
280         Action setdCG = nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(epFwdCtxOrds.getCgId()));
281         Action setNextHop;
282         String nextHop=null;
283
284         OfOverlayContext ofc = l2Ep.getAugmentation(OfOverlayContext.class);
285         LocationType location;
286
287         if (ofc != null && ofc.getLocationType() != null) {
288             location = ofc.getLocationType();
289         } else if (ofc != null) {
290             // Augmentation, but using default location
291             location = LocationType.Internal;
292         } else {
293             LOG.info("createL3PrefixFlow - Endpoint {} had no augmentation.", l2Ep);
294             return null;
295         }
296
297         long portNum = -1;
298
299         if (location.equals(LocationType.Internal)) {
300             checkNotNull(ofc.getNodeConnectorId());
301             nextHop = ofc.getNodeConnectorId().getValue();
302             try {
303                 portNum = getOfPortNum(ofc.getNodeConnectorId());
304             } catch (NumberFormatException ex) {
305                 LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
306                 return null;
307             }
308
309         } else {
310             // External
311             Set<NodeConnectorId> externalPorts = ctx.getSwitchManager().getExternalPorts(nodeId);
312             checkNotNull(externalPorts);
313             for (NodeConnectorId externalPort : externalPorts) {
314                 // TODO Bug #3440 Target: Be - should support for more than first external port.
315                 //TODO Bug 3546 - Difficult: External port is unrelated to Tenant, L3C, L2BD..
316                 nextHop = externalPort.getValue();
317                 try {
318                     portNum = getOfPortNum(externalPort);
319                 } catch (NumberFormatException ex) {
320                     LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
321                     return null;
322                 }
323                 continue;
324             }
325         }
326
327         if (Strings.isNullOrEmpty(nextHop)
328                 || portNum == -1) {
329             LOG.error("createL3Prefix - Cannot find nodeConnectorId for {} for Prefix: ", l2Ep, prefixEp);
330             return null;
331         }
332         setNextHop = nxLoadRegAction(NxmNxReg7.class, BigInteger.valueOf(portNum));
333
334         Action setDlDst = setDlDstAction(epDestMac);
335         l3ApplyActions.add(setDlDst);
336
337         Action decTtl = decNwTtlAction();
338         l3ApplyActions.add(decTtl);
339
340         order += 1;
341         applyActions.add(setdEPG);
342         applyActions.add(setdCG);
343         applyActions.add(setNextHop);
344
345         applyActions.addAll(l3ApplyActions);
346         Instruction applyActionsIns = new InstructionBuilder().setOrder(order++)
347             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
348             .build();
349
350         l3instructions.add(applyActionsIns);
351         Instruction gotoTable = new InstructionBuilder().setOrder(order++)
352             .setInstruction(gotoTableIns(ctx.getPolicyManager().getTABLEID_POLICY_ENFORCER()))
353             .build();
354         l3instructions.add(gotoTable);
355
356         Layer3Match m = null;
357         Long etherType = null;
358         String ikey = null;
359         Integer prefixLength=0;
360         if (prefixEp.getIpPrefix().getIpv4Prefix() != null) {
361             ikey = prefixEp.getIpPrefix().getIpv4Prefix().getValue();
362             etherType = IPv4;
363             prefixLength=Integer.valueOf(prefixEp.getIpPrefix().getIpv4Prefix().getValue().split("/")[1]);
364             m = new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(ikey)).build();
365         } else if (prefixEp.getIpPrefix().getIpv6Prefix() != null) {
366             ikey = prefixEp.getIpPrefix().getIpv6Prefix().getValue();
367             etherType = IPv6;
368             /*
369              *  This will result in flows with priority between 100-228, but since its matching on IPv6 prefix as well
370              *  this shouldn't pose and issue, as the priority is more important within the address space of the matcher,
371              *  even though technically flows are processed in priority order.
372              */
373
374             prefixLength=Integer.valueOf(prefixEp.getIpPrefix().getIpv6Prefix().getValue().split("/")[1]);
375             m = new Ipv6MatchBuilder().setIpv6Destination(new Ipv6Prefix(ikey)).build();
376         } else {
377             LOG.error("Endpoint has IPAddress that is not recognised as either IPv4 or IPv6.", prefixEp);
378             return null;
379         }
380
381         /*
382         // commented out because of the new FlowId implementation
383         FlowId flowid = new FlowId(new StringBuilder().append(Integer.toString(epFwdCtxOrds.getL3Id()))
384             .append("|l3prefix|")
385             .append(ikey)
386             .append("|")
387             .append(destSubnetGatewayMac)
388             .append("|")
389             .append(nextHop)
390             .toString());
391         */
392         MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, null, etherType));
393 //        MatchBuilder mb = new MatchBuilder();//.setLayer3Match(m);
394         addNxRegMatch(mb, RegMatch.of(NxmNxReg6.class, Long.valueOf(epFwdCtxOrds.getL3Id())));
395         Match match = mb.build();
396         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "L3prefix", match);
397         FlowBuilder flowb = base().setId(flowid)
398             .setPriority(Integer.valueOf(BASE_L3_PRIORITY+prefixLength))
399             .setMatch(match)
400             .setInstructions(new InstructionsBuilder().setInstruction(l3instructions).build());
401         return flowb.build();
402     }
403
404     private Flow createBroadcastFlow(EndpointFwdCtxOrdinals epOrd) {
405         MatchBuilder mb = new MatchBuilder()
406                             .setEthernetMatch(new EthernetMatchBuilder()
407                             .setEthernetDestination(new EthernetDestinationBuilder().
408                                                         setAddress(MULTICAST_MAC)
409                                                         .setMask(MULTICAST_MAC).build())
410                             .build());
411         addNxRegMatch(mb, RegMatch.of(NxmNxReg5.class, Long.valueOf(epOrd.getFdId())));
412
413         Match match = mb.build();
414         FlowId flowId = FlowIdUtils.newFlowId(TABLE_ID, "broadcast", match);
415         FlowBuilder flowb = base().setPriority(Integer.valueOf(140))
416             .setId(flowId)
417             .setMatch(match)
418             .setInstructions(
419                     instructions(applyActionIns(nxLoadTunIdAction(BigInteger.valueOf(epOrd.getFdId()), false),
420                             groupAction(Long.valueOf(epOrd.getFdId())))));
421
422         return flowb.build();
423     }
424
425     private boolean groupExists(NodeId nodeId, Integer fdId) throws Exception {
426         // Fetch existing GroupTables
427         if (ctx.getDataBroker() == null) {
428             return false;
429         }
430
431         ReadOnlyTransaction t = ctx.getDataBroker().newReadOnlyTransaction();
432         InstanceIdentifier<Node> niid = createNodePath(nodeId);
433         Optional<Node> r = t.read(LogicalDatastoreType.CONFIGURATION, niid).get();
434         if (!r.isPresent())
435             return false;
436         FlowCapableNode fcn = r.get().getAugmentation(FlowCapableNode.class);
437         if (fcn == null)
438             return false;
439
440         if (fcn.getGroup() != null) {
441             for (Group g : fcn.getGroup()) {
442                 if (g.getGroupId().getValue().equals(Long.valueOf(fdId))) { // Group
443                                                                             // Exists.
444                     return true;
445                 }
446             }
447         }
448         return false;
449     }
450
451     private MacAddress routerPortMac(L3Context l3c, IpAddress ipAddress) {
452
453         if (ctx.getDataBroker() == null) {
454             return null;
455         }
456
457         MacAddress defaultMacAddress = ROUTER_MAC;
458
459         EndpointL3Key l3Key = new EndpointL3Key(ipAddress, l3c.getId());
460         InstanceIdentifier<EndpointL3> endpointsIid = InstanceIdentifier.builder(Endpoints.class)
461             .child(EndpointL3.class, l3Key)
462             .build();
463         ReadOnlyTransaction t = ctx.getDataBroker().newReadOnlyTransaction();
464
465         Optional<EndpointL3> r;
466         try {
467             r = t.read(LogicalDatastoreType.OPERATIONAL, endpointsIid).get();
468             if (!r.isPresent())
469                 return defaultMacAddress;
470             EndpointL3 epL3 = r.get();
471             if (epL3.getMacAddress() == null) {
472                 return defaultMacAddress;
473             } else {
474                 return epL3.getMacAddress();
475             }
476         } catch (Exception e) {
477             LOG.error("Error reading EndpointL3 {}.{}", l3c, ipAddress, e);
478             return null;
479         }
480     }
481
482     private L3Context getL3ContextForSubnet(TenantId tenantId, Subnet sn) {
483         L3Context l3c = ctx.getPolicyResolver().getTenant(tenantId).resolveL3Context(sn.getId());
484         return l3c;
485     }
486
487     private Flow createRouterArpFlow(TenantId tenantId, NodeId nodeId, Subnet sn, int l3Id) {
488         if (sn == null || sn.getVirtualRouterIp() == null) {
489             LOG.trace("Didn't create routerArpFlow since either subnet or subnet virtual router was null");
490             return null;
491         }
492         /*
493          * TODO: Li alagalah: This should be new Yang "gateways" list as well,
494          * that expresses the gateway and prefixes it is interface for. Should
495          * also check for external.
496          */
497         if (sn.getVirtualRouterIp().getIpv4Address() != null) {
498             String ikey = sn.getVirtualRouterIp().getIpv4Address().getValue();
499
500             L3Context l3c = getL3ContextForSubnet(tenantId, sn);
501             if (l3c == null) {
502                 LOG.error("No L3 Context found associated with subnet {}", sn.getId());
503             }
504
505             MacAddress routerMac = routerPortMac(l3c, sn.getVirtualRouterIp());
506             if (routerMac == null) {
507                 return null;
508             }
509
510             BigInteger intRouterMac = new BigInteger(1, bytesFromHexString(routerMac.getValue()));
511
512             MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, null, ARP)).setLayer3Match(
513                     new ArpMatchBuilder().setArpOp(Integer.valueOf(1))
514                         .setArpTargetTransportAddress(new Ipv4Prefix(ikey + "/32"))
515                         .build());
516             addNxRegMatch(mb, RegMatch.of(NxmNxReg6.class, Long.valueOf(l3Id)));
517
518             Match match = mb.build();
519             FlowId flowId = FlowIdUtils.newFlowId(TABLE_ID, "routerarp", match);
520             FlowBuilder flowb = base().setPriority(150)
521                 .setId(flowId)
522                 .setMatch(match)
523                 .setInstructions(
524                         instructions(applyActionIns(nxMoveEthSrcToEthDstAction(), setDlSrcAction(routerMac),
525                                 nxLoadArpOpAction(BigInteger.valueOf(2L)), nxMoveArpShaToArpThaAction(),
526                                 nxLoadArpShaAction(intRouterMac), nxMoveArpSpaToArpTpaAction(),
527                                 nxLoadArpSpaAction(ikey), outputAction(new NodeConnectorId(nodeId.getValue()
528                                         + ":INPORT")))));
529             return flowb.build();
530         } else {
531             LOG.warn("IPv6 virtual router {} for subnet {} not supported", sn.getVirtualRouterIp(), sn.getId()
532                 .getValue());
533             return null;
534         }
535
536     }
537
538     private Flow createLocalL2Flow(Endpoint ep, EndpointFwdCtxOrdinals epFwdCtxOrds, OfOverlayContext ofc) {
539
540         // TODO Li alagalah - refactor common code but keep simple method
541         ArrayList<Instruction> instructions = new ArrayList<>();
542         List<Action> applyActions = new ArrayList<>();
543
544         int order = 0;
545
546         Action setdEPG = nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(epFwdCtxOrds.getEpgId()));
547         Action setdCG = nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(epFwdCtxOrds.getCgId()));
548         Action setNextHop;
549         String nextHop;
550
551         // BEGIN L2 LOCAL
552         nextHop = ofc.getNodeConnectorId().getValue();
553
554         long portNum;
555         try {
556             portNum = getOfPortNum(ofc.getNodeConnectorId());
557         } catch (NumberFormatException ex) {
558             LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
559             return null;
560         }
561
562         setNextHop = nxLoadRegAction(NxmNxReg7.class, BigInteger.valueOf(portNum));
563
564         // END L2 LOCAL
565
566         order += 1;
567         applyActions.add(setdEPG);
568         applyActions.add(setdCG);
569         applyActions.add(setNextHop);
570         Instruction applyActionsIns = new InstructionBuilder().setOrder(order++)
571             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
572             .build();
573         instructions.add(applyActionsIns);
574
575         Instruction gotoTable = new InstructionBuilder().setOrder(order++)
576             .setInstruction(gotoTableIns(ctx.getPolicyManager().getTABLEID_POLICY_ENFORCER()))
577             .build();
578         instructions.add(gotoTable);
579
580         MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, ep.getMacAddress(), null));
581         addNxRegMatch(mb, RegMatch.of(NxmNxReg4.class, Long.valueOf(epFwdCtxOrds.getBdId())));
582         Match match = mb.build();
583         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "localL2", match);
584         FlowBuilder flowb = base().setId(flowid)
585             .setPriority(Integer.valueOf(50))
586             .setMatch(match)
587             .setInstructions(new InstructionsBuilder().setInstruction(instructions).build());
588         return flowb.build();
589     }
590
591     private void syncEP(FlowMap flowMap, NodeId nodeId, PolicyInfo policyInfo, Endpoint srcEp, Endpoint destEp)
592             throws Exception {
593
594         // TODO: Conditions messed up, but for now, send policyInfo until this
595         // is fixed.
596         EndpointFwdCtxOrdinals destEpFwdCtxOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx, policyInfo, destEp);
597         EndpointFwdCtxOrdinals srcEpFwdCtxOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx, policyInfo, srcEp);
598
599         if (destEp.getTenant() == null || (destEp.getEndpointGroup() == null && destEp.getEndpointGroups() == null)) {
600             LOG.trace("Didn't process endpoint due to either tenant, or EPG(s) being null", destEp.getKey());
601             return;
602         }
603         OfOverlayContext ofc = destEp.getAugmentation(OfOverlayContext.class);
604
605         // ////////////////////////////////////////////////////////////////////////////////////////
606         /*
607          * NOT HANDLING EXTERNALS TODO: alagalah Li: External Gateway
608          * functionality needed here.
609          */
610         if (LocationType.External.equals(ofc.getLocationType())) {
611             // XXX - TODO - perform NAT and send to the external network
612             // TODO: Use case neutron gateway interface
613             LOG.warn("External endpoints not yet supported");
614             return;
615         }
616
617         /*
618          * Only care about subnets for L3, but fetch them before loop. We need
619          * the local subnets for setting SRC MAC for routing. All Routing is now
620          * done locally! YAY! Instead of being shovelled L2 style across network
621          * ala Helium.
622          */
623         List<Subnet> localSubnets = getLocalSubnets(nodeId);
624         if (localSubnets == null) {
625             LOG.error("No subnets could be found locally for node: {}", nodeId);
626             return;
627         }
628
629         if (Objects.equals(ofc.getNodeId(), nodeId)) {
630             // this is a local endpoint; send to the approppriate local
631             // port
632
633             if (srcEpFwdCtxOrds.getBdId() == destEpFwdCtxOrds.getBdId()) {
634                 flowMap.writeFlow(nodeId, TABLE_ID, createLocalL2Flow(destEp, destEpFwdCtxOrds, ofc));
635             }
636             // TODO Li alagalah: Need to move to EndpointL3 for L3 processing.
637             // The Endpoint conflation must end!
638             if (destEp.getL3Address() == null) {
639                 LOG.trace("Endpoint {} didn't have L3 Address so was not processed for L3 flows.", destEp.getKey());
640                 return;
641             }
642
643             for (L3Address l3a : destEp.getL3Address()) {
644                 if (l3a.getIpAddress() == null || l3a.getL3Context() == null) {
645                     LOG.error("Endpoint with L3Address but either IPAddress or L3Context is null. {}",
646                             destEp.getL3Address());
647                     continue;
648                 } else {
649                     for (Subnet localSubnet : localSubnets) {
650                         Flow flow = createLocalL3RoutedFlow(destEp, l3a, destEpFwdCtxOrds, ofc, localSubnet);
651                         if (flow != null) {
652                             flowMap.writeFlow(nodeId, TABLE_ID, flow);
653                         } else {
654                             LOG.trace("Did not write remote L3 flow for endpoint {} and subnet {}", l3a.getIpAddress(),
655                                     localSubnet.getIpPrefix().getValue());
656                         }
657                     }
658                 }
659             }
660         } else {
661             // this endpoint is on a different switch; send to the
662             // appropriate tunnel
663             if (srcEpFwdCtxOrds.getBdId() == destEpFwdCtxOrds.getBdId()) {
664                 Flow remoteL2Flow = createRemoteL2Flow(destEp, nodeId, srcEpFwdCtxOrds, destEpFwdCtxOrds, ofc);
665                 if (remoteL2Flow != null) {
666                     flowMap.writeFlow(nodeId, TABLE_ID, remoteL2Flow);
667                 }
668             } else {
669                 LOG.trace("DestinationMapper: RemoteL2Flow: not created, in different BDs src: {} dst: {}",
670                         srcEpFwdCtxOrds.getBdId(), destEpFwdCtxOrds.getBdId());
671             }
672
673             // TODO Li alagalah: Need to move to EndpointL3 for L3 processing.
674             // The Endpoint conflation must end!
675             if (destEp.getL3Address() == null) {
676                 LOG.trace("Endpoint {} didn't have L3 Address so was not processed for L3 flows.", destEp.getKey());
677                 return;
678             }
679             for (L3Address l3a : destEp.getL3Address()) {
680                 if (l3a.getIpAddress() == null || l3a.getL3Context() == null) {
681                     LOG.error("Endpoint with L3Address but either IPAddress or L3Context is null. {}",
682                             destEp.getL3Address());
683                     continue;
684                 } else {
685                     for (Subnet localSubnet : localSubnets) {
686                         Flow remoteL3Flow = createRemoteL3RoutedFlow(destEp, l3a, nodeId, srcEpFwdCtxOrds,
687                                 destEpFwdCtxOrds, ofc, localSubnet);
688                         if (remoteL3Flow != null) {
689                             flowMap.writeFlow(nodeId, TABLE_ID, remoteL3Flow);
690                         } else {
691                             LOG.trace("Did not write remote L3 flow for endpoint {} and subnet {}", l3a.getIpAddress(),
692                                     localSubnet.getIpPrefix().getValue());
693                         }
694                     }
695                 }
696             }
697         } // remote (tunnel)
698
699         // }
700
701     }
702
703     /*
704      * ################################## DestMapper Flow methods
705      * ##################################
706      */
707     private Flow createLocalL3RoutedFlow(Endpoint destEp, L3Address destL3Address, EndpointFwdCtxOrdinals epFwdCtxOrds,
708             OfOverlayContext ofc, Subnet srcSubnet) {
709
710         // TODO Li alagalah - refactor common code but keep simple method
711
712         Subnet destSubnet = null;
713         HashSet<Subnet> subnets = getSubnets(destEp.getTenant());
714         if (subnets == null) {
715             LOG.trace("No subnets in tenant {}", destEp.getTenant());
716             return null;
717         }
718         NetworkDomainId epNetworkContainment = getEPNetworkContainment(destEp);
719         for (Subnet subnet : subnets) {
720             // TODO Li alagalah add IPv6 support
721             if (subnet.getId().getValue().equals(epNetworkContainment.getValue())) {
722                 destSubnet = subnet;
723                 break;
724             }
725         }
726         if (destSubnet == null) {
727             LOG.trace("Destination IP address does not match any subnet in tenant {}", destL3Address.getIpAddress());
728             return null;
729         }
730
731         if (destSubnet.getVirtualRouterIp() == null) {
732             LOG.trace("Destination subnet {} for Endpoint {}.{} has no gateway IP", destSubnet.getIpPrefix(),
733                     destL3Address.getKey());
734             return null;
735         }
736
737         if (srcSubnet.getVirtualRouterIp() == null) {
738             LOG.trace("Local subnet {} has no gateway IP", srcSubnet.getIpPrefix());
739             return null;
740         }
741         L3Context destL3c = getL3ContextForSubnet(destEp.getTenant(), destSubnet);
742         if (destL3c == null || destL3c.getId() == null) {
743             LOG.error("No L3 Context found associated with subnet {}", destSubnet.getId());
744             return null;
745         }
746         L3Context srcL3c = getL3ContextForSubnet(destEp.getTenant(), srcSubnet);
747         if (srcL3c == null || srcL3c.getId() == null) {
748             LOG.error("No L3 Context found associated with subnet {}", srcSubnet.getId());
749             return null;
750         }
751
752         if (!(srcL3c.getId().getValue().equals(destL3c.getId().getValue()))) {
753             LOG.trace("Trying to route between two L3Contexts {} and {}. Not currently supported.", srcL3c.getId()
754                 .getValue(), destL3c.getId().getValue());
755             return null;
756         }
757
758         MacAddress matcherMac = routerPortMac(destL3c, srcSubnet.getVirtualRouterIp());
759         MacAddress epDestMac = destEp.getMacAddress();
760         MacAddress destSubnetGatewayMac = routerPortMac(destL3c, destSubnet.getVirtualRouterIp());
761
762         if (srcSubnet.getId().getValue().equals(destSubnet.getId().getValue())) {
763             // This is our final destination, so match on actual EP mac.
764             matcherMac = epDestMac;
765         }
766
767         ArrayList<Instruction> l3instructions = new ArrayList<>();
768         List<Action> applyActions = new ArrayList<>();
769         List<Action> l3ApplyActions = new ArrayList<>();
770
771         int order = 0;
772
773         Action setdEPG = nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(epFwdCtxOrds.getEpgId()));
774         Action setdCG = nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(epFwdCtxOrds.getCgId()));
775         Action setNextHop;
776         String nextHop;
777
778         // BEGIN L3 LOCAL
779         nextHop = ofc.getNodeConnectorId().getValue();
780
781         long portNum;
782         try {
783             portNum = getOfPortNum(ofc.getNodeConnectorId());
784         } catch (NumberFormatException ex) {
785             LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
786             return null;
787         }
788
789         setNextHop = nxLoadRegAction(NxmNxReg7.class, BigInteger.valueOf(portNum));
790         // END L3 LOCAL
791
792         // Lets not re-write the srcMac if its local.
793         if (!(matcherMac.getValue().equals(epDestMac.getValue()))) {
794             Action setDlSrc = setDlSrcAction(destSubnetGatewayMac);
795             l3ApplyActions.add(setDlSrc);
796         }
797
798         Action setDlDst = setDlDstAction(epDestMac);
799         l3ApplyActions.add(setDlDst);
800
801         Action decTtl = decNwTtlAction();
802         l3ApplyActions.add(decTtl);
803
804         order += 1;
805         applyActions.add(setdEPG);
806         applyActions.add(setdCG);
807         applyActions.add(setNextHop);
808
809         applyActions.addAll(l3ApplyActions);
810         Instruction applyActionsIns = new InstructionBuilder().setOrder(order++)
811             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
812             .build();
813
814         l3instructions.add(applyActionsIns);
815         Instruction gotoTable = new InstructionBuilder().setOrder(order++)
816             .setInstruction(gotoTableIns(ctx.getPolicyManager().getTABLEID_POLICY_ENFORCER()))
817             .build();
818         l3instructions.add(gotoTable);
819         Layer3Match m = null;
820         Long etherType = null;
821         String ikey = null;
822         if (destL3Address.getIpAddress().getIpv4Address() != null) {
823             ikey = destL3Address.getIpAddress().getIpv4Address().getValue() + "/32";
824             etherType = IPv4;
825             m = new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(ikey)).build();
826         } else if (destL3Address.getIpAddress().getIpv6Address() != null) {
827             ikey = destL3Address.getIpAddress().getIpv6Address().getValue() + "/128";
828             etherType = IPv6;
829             m = new Ipv6MatchBuilder().setIpv6Destination(new Ipv6Prefix(ikey)).build();
830         } else {
831             LOG.error("Endpoint has IPAddress that is not recognised as either IPv4 or IPv6.", destL3Address.toString());
832             return null;
833         }
834
835         MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, matcherMac, etherType))
836             .setLayer3Match(m);
837         addNxRegMatch(mb, RegMatch.of(NxmNxReg6.class, Long.valueOf(epFwdCtxOrds.getL3Id())));
838         Match match = mb.build();
839         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "localL3", match);
840         FlowBuilder flowb = base().setId(flowid)
841             .setPriority(Integer.valueOf(132))
842             .setMatch(match)
843             .setInstructions(new InstructionsBuilder().setInstruction(l3instructions).build());
844         return flowb.build();
845     }
846
847     private Flow createRemoteL2Flow(Endpoint ep, NodeId nodeId, EndpointFwdCtxOrdinals srcEpFwdCtxOrds,
848             EndpointFwdCtxOrdinals destEpFwdCtxOrds, OfOverlayContext ofc) {
849
850         // TODO Li alagalah - refactor common code but keep simple method
851
852         // this endpoint is on a different switch; send to the
853         // appropriate tunnel
854
855         ArrayList<Instruction> instructions = new ArrayList<>();
856         List<Action> applyActions = new ArrayList<>();
857
858         int order = 0;
859
860         Action setdEPG = nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(destEpFwdCtxOrds.getEpgId()));
861         Action setdCG = nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(destEpFwdCtxOrds.getCgId()));
862         Action setNextHop;
863         String nextHop;
864
865         // BEGIN TUNNEL HANDLING
866         IpAddress tunDst = ctx.getSwitchManager().getTunnelIP(ofc.getNodeId(), TunnelTypeVxlan.class);
867         NodeConnectorId tunPort = ctx.getSwitchManager().getTunnelPort(nodeId, TunnelTypeVxlan.class);
868         if (tunDst == null) {
869             LOG.warn("Failed to get Tunnel IP for NodeId {} with EP {}", nodeId, ep);
870             return null;
871         }
872         if (tunPort == null) {
873             LOG.warn("Failed to get Tunnel Port for NodeId {} with EP {}", nodeId, ep);
874             return null;
875         }
876
877         Action tundstAction;
878
879         if (tunDst.getIpv4Address() != null) {
880             nextHop = tunDst.getIpv4Address().getValue();
881             tundstAction = nxLoadTunIPv4Action(nextHop, false);
882         } else if (tunDst.getIpv6Address() != null) {
883             // nextHop = tunDst.getIpv6Address().getValue();
884             LOG.error("IPv6 tunnel destination {} for {} not supported", tunDst.getIpv6Address().getValue(),
885                     ofc.getNodeId());
886             return null;
887         } else {
888             // this shouldn't happen
889             LOG.error("Tunnel IP for {} invalid", ofc.getNodeId());
890             return null;
891         }
892
893         long portNum;
894         try {
895             portNum = getOfPortNum(tunPort);
896         } catch (NumberFormatException ex) {
897             LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
898             return null;
899         }
900
901         setNextHop = nxLoadRegAction(NxmNxReg7.class, BigInteger.valueOf(portNum));
902         applyActions.add(tundstAction);
903         // END TUNNEL
904
905         order += 1;
906         applyActions.add(setdEPG);
907         applyActions.add(setdCG);
908         applyActions.add(setNextHop);
909         Instruction applyActionsIns = new InstructionBuilder().setOrder(order++)
910             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
911             .build();
912         instructions.add(applyActionsIns);
913
914         applyActionsIns = new InstructionBuilder().setOrder(order++)
915             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
916             .build();
917
918         Instruction gotoTable = new InstructionBuilder().setOrder(order++)
919             .setInstruction(gotoTableIns(ctx.getPolicyManager().getTABLEID_POLICY_ENFORCER()))
920             .build();
921         instructions.add(gotoTable);
922
923         MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, ep.getMacAddress(), null));
924         addNxRegMatch(mb, RegMatch.of(NxmNxReg4.class, Long.valueOf(destEpFwdCtxOrds.getBdId())));
925         Match match = mb.build();
926         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "remoteL2", match);
927         FlowBuilder flowb = base().setId(flowid)
928             .setPriority(Integer.valueOf(50))
929             .setMatch(match)
930             .setInstructions(new InstructionsBuilder().setInstruction(instructions).build());
931
932         return flowb.build();
933     }
934
935     private Flow createRemoteL3RoutedFlow(Endpoint destEp, L3Address destL3Address, NodeId nodeId,
936             EndpointFwdCtxOrdinals srcEpFwdCtxOrds, EndpointFwdCtxOrdinals destEpFwdCtxOrds, OfOverlayContext ofc,
937             Subnet srcSubnet) {
938
939         // TODO Li alagalah - refactor common code but keep simple method
940
941         // this endpoint is on a different switch; send to the
942         // appropriate tunnel
943         Subnet destSubnet = null;
944         HashSet<Subnet> subnets = getSubnets(destEp.getTenant());
945         if (subnets == null) {
946             LOG.trace("No subnets in tenant {}", destEp.getTenant());
947             return null;
948         }
949         NetworkDomainId epNetworkContainment = getEPNetworkContainment(destEp);
950         for (Subnet subnet : subnets) {
951             // TODO Li alagalah add IPv6 support
952             if (subnet.getId().getValue().equals(epNetworkContainment.getValue())) {
953                 destSubnet = subnet;
954                 break;
955             }
956         }
957         if (destSubnet == null) {
958             LOG.info("Destination IP address does not match any subnet in tenant {}", destL3Address.getIpAddress());
959             return null;
960         }
961
962         if (destSubnet.getVirtualRouterIp() == null) {
963             LOG.trace("Destination subnet {} for Endpoint {}.{} has no gateway IP", destSubnet.getIpPrefix(),
964                     destL3Address.getKey());
965             return null;
966         }
967
968         if (srcSubnet.getVirtualRouterIp() == null) {
969             LOG.trace("Local subnet {} has no gateway IP", srcSubnet.getIpPrefix());
970             return null;
971         }
972         L3Context destL3c = getL3ContextForSubnet(destEp.getTenant(), destSubnet);
973         if (destL3c == null || destL3c.getId() == null) {
974             LOG.error("No L3 Context found associated with subnet {}", destSubnet.getId());
975             return null;
976         }
977         L3Context srcL3c = getL3ContextForSubnet(destEp.getTenant(), srcSubnet);
978         if (srcL3c == null || srcL3c.getId() == null) {
979             LOG.error("No L3 Context found associated with subnet {}", srcSubnet.getId());
980             return null;
981         }
982
983         if (!(srcL3c.getId().getValue().equals(destL3c.getId().getValue()))) {
984             LOG.trace("Trying to route between two L3Contexts {} and {}. Not currently supported.", srcL3c.getId()
985                 .getValue(), destL3c.getId().getValue());
986             return null;
987         }
988
989         MacAddress matcherMac = routerPortMac(destL3c, srcSubnet.getVirtualRouterIp());
990         MacAddress epDestMac = destEp.getMacAddress();
991         MacAddress destSubnetGatewayMac = routerPortMac(destL3c, destSubnet.getVirtualRouterIp());
992
993         ArrayList<Instruction> l3instructions = new ArrayList<>();
994         List<Action> applyActions = new ArrayList<>();
995         List<Action> l3ApplyActions = new ArrayList<>();
996
997         int order = 0;
998
999         Action setdEPG = nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(destEpFwdCtxOrds.getEpgId()));
1000         Action setdCG = nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(destEpFwdCtxOrds.getCgId()));
1001         Action setNextHop;
1002         String nextHop;
1003
1004         // BEGIN TUNNEL HANDLING
1005         IpAddress tunDst = ctx.getSwitchManager().getTunnelIP(ofc.getNodeId(), TunnelTypeVxlan.class);
1006         NodeConnectorId tunPort = ctx.getSwitchManager().getTunnelPort(nodeId, TunnelTypeVxlan.class);
1007         if (tunDst == null) {
1008             LOG.warn("Failed to get Tunnel IP for NodeId {} with L3Address {}", nodeId, destL3Address);
1009             return null;
1010         }
1011         if (tunPort == null) {
1012             LOG.warn("Failed to get Tunnel port for NodeId {} with L3Address {}", nodeId, destL3Address);
1013             return null;
1014         }
1015
1016         Action tundstAction;
1017
1018         if (tunDst.getIpv4Address() != null) {
1019             nextHop = tunDst.getIpv4Address().getValue();
1020             tundstAction = nxLoadTunIPv4Action(nextHop, false);
1021         } else if (tunDst.getIpv6Address() != null) {
1022             // nextHop = tunDst.getIpv6Address().getValue();
1023             LOG.error("IPv6 tunnel destination {} for {} not supported", tunDst.getIpv6Address().getValue(),
1024                     ofc.getNodeId());
1025             return null;
1026         } else {
1027             // this shouldn't happen
1028             LOG.error("Tunnel IP for {} invalid", ofc.getNodeId());
1029             return null;
1030         }
1031
1032         long portNum;
1033         try {
1034             portNum = getOfPortNum(tunPort);
1035         } catch (NumberFormatException ex) {
1036             LOG.warn("Could not parse port number {}", ofc.getNodeConnectorId(), ex);
1037             return null;
1038         }
1039
1040         setNextHop = nxLoadRegAction(NxmNxReg7.class, BigInteger.valueOf(portNum));
1041         applyActions.add(tundstAction);
1042         // END TUNNEL
1043
1044         order += 1;
1045         applyActions.add(setdEPG);
1046         applyActions.add(setdCG);
1047         applyActions.add(setNextHop);
1048
1049         Action setDlSrc = setDlSrcAction(destSubnetGatewayMac);
1050         l3ApplyActions.add(setDlSrc);
1051
1052         Action setDlDst = setDlDstAction(epDestMac);
1053         l3ApplyActions.add(setDlDst);
1054
1055         Action decTtl = decNwTtlAction();
1056         l3ApplyActions.add(decTtl);
1057
1058         applyActions.addAll(l3ApplyActions);
1059         Instruction applyActionsIns = new InstructionBuilder().setOrder(order++)
1060             .setInstruction(applyActionIns(applyActions.toArray(new Action[applyActions.size()])))
1061             .build();
1062
1063         l3instructions.add(applyActionsIns);
1064         Instruction gotoTable = new InstructionBuilder().setOrder(order++)
1065             .setInstruction(gotoTableIns(ctx.getPolicyManager().getTABLEID_POLICY_ENFORCER()))
1066             .build();
1067         l3instructions.add(gotoTable);
1068         Layer3Match m = null;
1069         Long etherType = null;
1070         String ikey = null;
1071         if (destL3Address.getIpAddress().getIpv4Address() != null) {
1072             ikey = destL3Address.getIpAddress().getIpv4Address().getValue() + "/32";
1073             etherType = IPv4;
1074             m = new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(ikey)).build();
1075         } else if (destL3Address.getIpAddress().getIpv6Address() != null) {
1076             ikey = destL3Address.getIpAddress().getIpv6Address().getValue() + "/128";
1077             etherType = IPv6;
1078             m = new Ipv6MatchBuilder().setIpv6Destination(new Ipv6Prefix(ikey)).build();
1079         } else {
1080             LOG.error("Endpoint has IPAddress that is not recognised as either IPv4 or IPv6.", destL3Address.toString());
1081             return null;
1082         }
1083
1084         MatchBuilder mb = new MatchBuilder().setEthernetMatch(ethernetMatch(null, matcherMac, etherType))
1085             .setLayer3Match(m);
1086         addNxRegMatch(mb, RegMatch.of(NxmNxReg6.class, Long.valueOf(destEpFwdCtxOrds.getL3Id())));
1087         Match match = mb.build();
1088         FlowId flowid = FlowIdUtils.newFlowId(TABLE_ID, "remoteL3", match);
1089         FlowBuilder flowb = base().setId(flowid)
1090             .setPriority(Integer.valueOf(132))
1091             .setMatch(match)
1092             .setInstructions(new InstructionsBuilder().setInstruction(l3instructions).build());
1093         return flowb.build();
1094     }
1095
1096     private NetworkDomainId getEPNetworkContainment(Endpoint endpoint) {
1097         if (endpoint.getNetworkContainment() != null) {
1098             return endpoint.getNetworkContainment();
1099         } else {
1100             /*
1101              * TODO: Be alagalah: Endpoint Refactor: This should be set on input
1102              * which we can't do because of the backwards way endpoints were
1103              * "architected".
1104              */
1105             return ctx.getPolicyResolver()
1106                 .getTenant(endpoint.getTenant())
1107                 .getEndpointGroup(endpoint.getEndpointGroup())
1108                 .getNetworkDomain();
1109         }
1110     }
1111
1112     private HashSet<Subnet> getSubnets(final TenantId tenantId) {
1113
1114         // if (subnetsByTenant.get(tenantId) != null) {
1115         // return subnetsByTenant.get(tenantId);
1116         // }
1117
1118         if (ctx.getDataBroker() == null) {
1119             return null;
1120         }
1121
1122         ReadOnlyTransaction t = ctx.getDataBroker().newReadOnlyTransaction();
1123         InstanceIdentifier<Tenant> tiid = TenantUtils.tenantIid(tenantId);
1124         Optional<Tenant> tenantInfo;
1125         try {
1126             tenantInfo = t.read(LogicalDatastoreType.CONFIGURATION, tiid).get();
1127         } catch (Exception e) {
1128             LOG.error("Could not read Tenant {}", tenantId, e);
1129             return null;
1130         }
1131
1132         HashSet<Subnet> subnets = new HashSet<Subnet>();
1133
1134         if (!tenantInfo.isPresent()) {
1135             LOG.warn("Tenant {} not found", tenantId);
1136             return null;
1137         }
1138
1139         subnets.addAll(tenantInfo.get().getSubnet());
1140         // subnetsByTenant.put(tenantId, subnets);
1141         return subnets;
1142     }
1143
1144     // Need a method to get subnets for EPs attached to the node locally
1145     // to set the source Mac address for the router interface.
1146     private List<Subnet> getLocalSubnets(NodeId nodeId) {
1147         Collection<Endpoint> endpointsForNode = ctx.getEndpointManager().getEndpointsForNode(nodeId);
1148
1149         List<Subnet> localSubnets = new ArrayList<Subnet>();
1150
1151         for (Endpoint endpoint : endpointsForNode) {
1152             HashSet<Subnet> subnets = getSubnets(endpoint.getTenant());
1153             if (subnets == null) {
1154                 LOG.error("No local subnets.");
1155                 return null;
1156             }
1157             NetworkDomainId epNetworkContainment = getEPNetworkContainment(endpoint);
1158             for (Subnet subnet : subnets) {
1159                 if (epNetworkContainment.getValue().equals(subnet.getId().getValue())) {
1160                     localSubnets.add(subnet);
1161                 }
1162             }
1163         }
1164         return localSubnets;
1165     }
1166
1167     static byte[] bytesFromHexString(String values) {
1168         String target = "";
1169         if (values != null) {
1170             target = values;
1171         }
1172         String[] octets = target.split(":");
1173
1174         byte[] ret = new byte[octets.length];
1175         for (int i = 0; i < octets.length; i++) {
1176             ret[i] = Integer.valueOf(octets[i], 16).byteValue();
1177         }
1178         return ret;
1179     }
1180 }