Datastore-constrained txes: elanmanager
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / internal / ElanPacketInHandler.java
1 /*
2  * Copyright (c) 2016, 2018 Ericsson India Global Services Pvt Ltd. 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 package org.opendaylight.netvirt.elan.internal;
9
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
11 import static org.opendaylight.genius.infra.Datastore.OPERATIONAL;
12
13 import com.google.common.base.Optional;
14 import com.google.common.util.concurrent.ListenableFuture;
15
16 import java.math.BigInteger;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.List;
20
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
27 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
28 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
29 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
30 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
31 import org.opendaylight.genius.mdsalutil.NWUtil;
32 import org.opendaylight.genius.mdsalutil.NwConstants;
33 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
34 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
35 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
36 import org.opendaylight.netvirt.elan.cache.ElanInstanceCache;
37 import org.opendaylight.netvirt.elan.evpn.utils.EvpnUtils;
38 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
39 import org.opendaylight.netvirt.elan.utils.ElanUtils;
40 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
41 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.NoMatch;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInReason;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @Singleton
60 public class ElanPacketInHandler implements PacketProcessingListener {
61
62     private static final Logger LOG = LoggerFactory.getLogger(ElanPacketInHandler.class);
63
64     private final ManagedNewTransactionRunner txRunner;
65     private final IInterfaceManager interfaceManager;
66     private final ElanUtils elanUtils;
67     private final ElanL2GatewayUtils elanL2GatewayUtils;
68     private final EvpnUtils evpnUtils;
69     private final JobCoordinator jobCoordinator;
70     private final ElanInstanceCache elanInstanceCache;
71     private final ElanManagerCounters elanManagerCounters;
72
73     @Inject
74     public ElanPacketInHandler(DataBroker dataBroker, final IInterfaceManager interfaceManager, ElanUtils elanUtils,
75             EvpnUtils evpnUtils, ElanL2GatewayUtils elanL2GatewayUtils, JobCoordinator jobCoordinator,
76             ElanInstanceCache elanInstanceCache, ElanManagerCounters elanManagerCounters) {
77         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
78         this.interfaceManager = interfaceManager;
79         this.elanUtils = elanUtils;
80         this.elanL2GatewayUtils = elanL2GatewayUtils;
81         this.evpnUtils = evpnUtils;
82         this.jobCoordinator = jobCoordinator;
83         this.elanInstanceCache = elanInstanceCache;
84         this.elanManagerCounters = elanManagerCounters;
85     }
86
87     @Override
88     public void onPacketReceived(PacketReceived notification) {
89         Class<? extends PacketInReason> pktInReason = notification.getPacketInReason();
90         short tableId = notification.getTableId().getValue();
91         if (pktInReason == NoMatch.class && tableId == NwConstants.ELAN_SMAC_TABLE) {
92             elanManagerCounters.unknownSmacPktinRcv();
93             try {
94                 byte[] data = notification.getPayload();
95                 Ethernet res = new Ethernet();
96
97                 res.deserialize(data, 0, data.length * NetUtils.NUM_BITS_IN_A_BYTE);
98
99                 byte[] srcMac = res.getSourceMACAddress();
100                 final String macAddress = NWUtil.toStringMacAddress(srcMac);
101                 final BigInteger metadata = notification.getMatch().getMetadata().getMetadata();
102                 final long elanTag = MetaDataUtil.getElanTagFromMetadata(metadata);
103
104                 long portTag = MetaDataUtil.getLportFromMetadata(metadata).intValue();
105
106                 Optional<IfIndexInterface> interfaceInfoOp = elanUtils.getInterfaceInfoByInterfaceTag(portTag);
107                 if (!interfaceInfoOp.isPresent()) {
108                     LOG.warn("There is no interface for given portTag {}", portTag);
109                     return;
110                 }
111                 String interfaceName = interfaceInfoOp.get().getInterfaceName();
112                 LOG.debug("Received a packet with srcMac: {} ElanTag: {} PortTag: {} InterfaceName: {}", macAddress,
113                         elanTag, portTag, interfaceName);
114                 ElanTagName elanTagName = elanUtils.getElanInfoByElanTag(elanTag);
115                 if (elanTagName == null) {
116                     LOG.warn("not able to find elanTagName in elan-tag-name-map for elan tag {}", elanTag);
117                     return;
118                 }
119                 ElanInterfaceMac elanInterfaceMac = elanUtils.getElanInterfaceMacByInterfaceName(interfaceName);
120                 if (elanInterfaceMac == null) {
121                     LOG.info("There is no ElanInterfaceForwardingEntryDS created for interface :{}", interfaceName);
122                     return;
123                 }
124                 String elanName = elanTagName.getName();
125                 PhysAddress physAddress = new PhysAddress(macAddress);
126                 MacEntry oldMacEntry = elanUtils.getMacEntryForElanInstance(elanName, physAddress).orNull();
127                 boolean isVlanOrFlatProviderIface = interfaceManager.isExternalInterface(interfaceName);
128
129                 Optional<IpAddress> srcIpAddress = elanUtils.getSourceIpAddress(res);
130                 MacEntry newMacEntry = null;
131                 BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
132                 if (!srcIpAddress.isPresent()) {
133                     newMacEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
134                             .withKey(new MacEntryKey(physAddress))
135                             .setControllerLearnedForwardingEntryTimestamp(timeStamp)
136                             .setIsStaticAddress(false).build();
137                 } else {
138                     newMacEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
139                             .setIpPrefix(srcIpAddress.get()).withKey(new MacEntryKey(physAddress))
140                             .setControllerLearnedForwardingEntryTimestamp(timeStamp)
141                             .setIsStaticAddress(false).build();
142                 }
143                 if (srcIpAddress.isPresent()) {
144                     String prefix = srcIpAddress.get().getIpv4Address().getValue();
145                     InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
146                     ElanInstance elanInstance = elanInstanceCache.get(elanName).orNull();
147                     evpnUtils.advertisePrefix(elanInstance, macAddress, prefix, interfaceName, interfaceInfo.getDpId());
148                 }
149                 enqueueJobForMacSpecificTasks(macAddress, elanTag, interfaceName, elanName, physAddress, oldMacEntry,
150                         newMacEntry, isVlanOrFlatProviderIface);
151
152                 ElanInstance elanInstance = elanInstanceCache.get(elanName).orNull();
153                 InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
154                 if (interfaceInfo == null) {
155                     LOG.trace("Interface:{} is not present under Config DS", interfaceName);
156                     return;
157                 }
158                 enqueueJobForDPNSpecificTasks(macAddress, elanTag, interfaceName, physAddress, elanInstance,
159                         interfaceInfo, oldMacEntry, newMacEntry, isVlanOrFlatProviderIface);
160
161
162             } catch (PacketException e) {
163                 LOG.error("Failed to decode packet: {}", notification, e);
164             }
165         }
166     }
167
168     private void enqueueJobForMacSpecificTasks(final String macAddress, final long elanTag, String interfaceName,
169                                                String elanName, PhysAddress physAddress,
170                                                MacEntry oldMacEntry, MacEntry newMacEntry,
171                                                final boolean isVlanOrFlatProviderIface) {
172         jobCoordinator.enqueueJob(ElanUtils.getElanMacKey(elanTag, macAddress),
173             () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
174                 if (oldMacEntry != null && oldMacEntry.getInterface().equals(interfaceName)) {
175                     // This should never occur because of ovs temporary mac learning
176                     elanManagerCounters.unknownSmacPktinForwardingEntriesRemoved();
177                 } else if (oldMacEntry != null && !isVlanOrFlatProviderIface) {
178                     long macTimeStamp = oldMacEntry.getControllerLearnedForwardingEntryTimestamp().longValue();
179                     if (System.currentTimeMillis() > macTimeStamp + 1000) {
180                         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
181                                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName,
182                                         physAddress);
183                         tx.delete(macEntryId);
184                     } else {
185                         // New FEs flood their packets on all interfaces. This can lead
186                         // to many contradicting packet_ins. Ignore all packets received
187                         // within 1s after the first packet_in
188                         elanManagerCounters.unknownSmacPktinMacMigrationIgnoredDueToProtection();
189                     }
190                 } else if (oldMacEntry != null) {
191                     elanManagerCounters.unknownSmacPktinRemovedForRelearned();
192                 }
193                 // This check is required only to update elan-forwarding-tables when mac is learned
194                 // in ports (example: VM interfaces) other than on vlan provider port.
195                 if (!isVlanOrFlatProviderIface && oldMacEntry == null) {
196                     InstanceIdentifier<MacEntry> elanMacEntryId =
197                             ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
198                     tx.put(elanMacEntryId, newMacEntry, WriteTransaction.CREATE_MISSING_PARENTS);
199                 }
200             })));
201     }
202
203     private void enqueueJobForDPNSpecificTasks(final String macAddress, final long elanTag, String interfaceName,
204                                                PhysAddress physAddress, ElanInstance elanInstance,
205                                                InterfaceInfo interfaceInfo, MacEntry oldMacEntry,
206                                                MacEntry newMacEntry, boolean isVlanOrFlatProviderIface) {
207         jobCoordinator.enqueueJob(ElanUtils.getElanMacDPNKey(elanTag, macAddress, interfaceInfo.getDpId()), () -> {
208             macMigrationFlowsCleanup(interfaceName, elanInstance, oldMacEntry, isVlanOrFlatProviderIface);
209             BigInteger dpId = interfaceManager.getDpnForInterface(interfaceName);
210             elanL2GatewayUtils.scheduleAddDpnMacInExtDevices(elanInstance.getElanInstanceName(), dpId,
211                     Collections.singletonList(physAddress));
212             elanManagerCounters.unknownSmacPktinLearned();
213             List<ListenableFuture<Void>> futures = new ArrayList<>();
214             futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
215                 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, operTx -> {
216                     elanUtils.setupMacFlows(elanInstance, interfaceInfo, elanInstance.getMacTimeout(),
217                         macAddress, !isVlanOrFlatProviderIface, tx);
218                     InstanceIdentifier<MacEntry> macEntryId =
219                         ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
220                     operTx.put(macEntryId, newMacEntry, WriteTransaction.CREATE_MISSING_PARENTS);
221                 }));
222             }));
223             return futures;
224         });
225     }
226
227     private void macMigrationFlowsCleanup(String interfaceName, ElanInstance elanInstance, MacEntry macEntry,
228                                           boolean isVlanOrFlatProviderIface) {
229         if (macEntry != null && !macEntry.getInterface().equals(interfaceName)
230                 && !isVlanOrFlatProviderIface) {
231             tryAndRemoveInvalidMacEntry(elanInstance.getElanInstanceName(), macEntry);
232             elanManagerCounters.unknownSmacPktinFlowsRemovedForRelearned();
233         }
234     }
235
236     /*
237      * Though this method is a little costlier because it uses try-catch
238      * construct, it is used only in rare scenarios like MAC movement or invalid
239      * Static MAC having been added on a wrong ELAN.
240      */
241     private void tryAndRemoveInvalidMacEntry(String elanName, MacEntry macEntry) {
242         ElanInstance elanInfo = elanInstanceCache.get(elanName).orNull();
243         if (elanInfo == null) {
244             LOG.warn("MAC {} is been added (either statically or dynamically) for an invalid Elan {}. "
245                     + "Manual cleanup may be necessary", macEntry.getMacAddress(), elanName);
246             return;
247         }
248
249         InterfaceInfo oldInterfaceLport = interfaceManager.getInterfaceInfo(macEntry.getInterface());
250         if (oldInterfaceLport == null) {
251             LOG.warn("MAC {} is been added (either statically or dynamically) on an invalid Logical Port {}. "
252                             + "Manual cleanup may be necessary",
253                     macEntry.getMacAddress(), macEntry.getInterface());
254             return;
255         }
256         ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
257             tx -> elanUtils.deleteMacFlows(elanInfo, oldInterfaceLport, macEntry, tx)), LOG,
258             "Error deleting invalid MAC entry");
259         elanL2GatewayUtils.removeMacsFromElanExternalDevices(elanInfo,
260                 Collections.singletonList(macEntry.getMacAddress()));
261     }
262
263 }