Merge "Multiple fixes related to VPN concurrency"
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / internal / ElanPacketInHandler.java
1 /*
2  * Copyright (c) 2016 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 com.google.common.base.Optional;
11 import java.math.BigInteger;
12 import java.util.Arrays;
13 import org.opendaylight.controller.liblldp.NetUtils;
14 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
15 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
16 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
17 import org.opendaylight.genius.mdsalutil.MDSALUtil;
18 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
19 import org.opendaylight.genius.mdsalutil.NWUtil;
20 import org.opendaylight.genius.mdsalutil.NwConstants;
21 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
22 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
23 import org.opendaylight.netvirt.elan.utils.ElanUtils;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.NoMatch;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInReason;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 @SuppressWarnings("deprecation")
40 public class ElanPacketInHandler implements PacketProcessingListener {
41
42     private ElanServiceProvider elanServiceProvider = null;
43     private static volatile ElanPacketInHandler elanPacketInHandler = null;
44     private static final Logger logger = LoggerFactory.getLogger(ElanPacketInHandler.class);
45
46     public ElanPacketInHandler(ElanServiceProvider elanServiceProvider) {
47         this.elanServiceProvider = elanServiceProvider;
48     }
49
50     public static ElanPacketInHandler getElanPacketInHandler(ElanServiceProvider elanServiceProvider) {
51         if (elanPacketInHandler == null) {
52             synchronized (ElanPacketInHandler.class) {
53                 if (elanPacketInHandler == null) {
54                     ElanPacketInHandler elanPacketInHandler = new ElanPacketInHandler(elanServiceProvider);
55                     return elanPacketInHandler;
56
57                 }
58             }
59         }
60         return elanPacketInHandler;
61     }
62
63     @Override
64     public void onPacketReceived(PacketReceived notification) {
65         Class<? extends PacketInReason> pktInReason = notification.getPacketInReason();
66         short tableId = notification.getTableId().getValue();
67         if (pktInReason == NoMatch.class && tableId == NwConstants.ELAN_SMAC_TABLE) {
68             try {
69                 byte[] data = notification.getPayload();
70                 Ethernet res = new Ethernet();
71
72                 res.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte);
73
74                 byte[] srcMac = res.getSourceMACAddress();
75                 String macAddress = NWUtil.toStringMacAddress(srcMac);
76                 PhysAddress physAddress = new PhysAddress(macAddress);
77                 BigInteger metadata = notification.getMatch().getMetadata().getMetadata();
78                 long elanTag = MetaDataUtil.getElanTagFromMetadata(metadata);
79
80                 long portTag = MetaDataUtil.getLportFromMetadata(metadata).intValue();
81
82                 Optional<IfIndexInterface> interfaceInfoOp = ElanUtils.getInterfaceInfoByInterfaceTag(portTag);
83                 if (!interfaceInfoOp.isPresent()) {
84                     logger.warn("There is no interface for given portTag {}", portTag);
85                     return;
86                 }
87                 String interfaceName = interfaceInfoOp.get().getInterfaceName();
88                 logger.debug("Received a packet with srcMac: {} ElanTag: {} PortTag: {} InterfaceName: {}", macAddress,
89                         elanTag, portTag, interfaceName);
90                 ElanTagName elanTagName = ElanUtils.getElanInfoByElanTag(elanTag);
91                 if (elanTagName == null) {
92                     logger.warn("not able to find elanTagName in elan-tag-name-map for elan tag {}", elanTag);
93                     return;
94                 }
95                 String elanName = elanTagName.getName();
96                 MacEntry macEntry = ElanUtils.getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
97                 if (macEntry != null && macEntry.getInterface() == interfaceName) {
98                     BigInteger macTimeStamp = macEntry.getControllerLearnedForwardingEntryTimestamp();
99                     if (System.currentTimeMillis() > macTimeStamp.longValue() + 2000) {
100                         /*
101                          * Protection time expired. Even though the MAC has been
102                          * learnt (it is in the cache) the packets are punted to
103                          * controller. Which means, the the flows were not
104                          * successfully created in the DPN, but the MAC entry
105                          * has been added successfully in the cache.
106                          *
107                          * So, the cache has to be cleared and the flows and
108                          * cache should be recreated (clearing of cache is
109                          * required so that the timestamp is updated).
110                          */
111                         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
112                                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
113                         ElanUtils.delete(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, macEntryId);
114                     } else {
115                         // Protection time running. Ignore packets for 2 seconds
116                         return;
117                     }
118                 } else if (macEntry != null) {
119                     // MAC address has moved. Overwrite the mapping and replace
120                     // MAC flows
121                     long macTimeStamp = macEntry.getControllerLearnedForwardingEntryTimestamp().longValue();
122                     if (System.currentTimeMillis() > macTimeStamp + 1000) {
123
124                         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
125                                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
126                         ElanUtils.delete(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, macEntryId);
127                         tryAndRemoveInvalidMacEntry(elanName, macEntry);
128                     } else {
129                         // New FEs flood their packets on all interfaces. This
130                         // can lead
131                         // to many contradicting packet_ins. Ignore all packets
132                         // received
133                         // within 1s after the first packet_in
134                         return;
135                     }
136                 }
137                 BigInteger timeStamp = new BigInteger(String.valueOf((long) System.currentTimeMillis()));
138                 macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
139                         .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
140                         .setIsStaticAddress(false).build();
141                 InstanceIdentifier<MacEntry> macEntryId = ElanUtils
142                         .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
143                 MDSALUtil.syncWrite(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, macEntryId,
144                         macEntry);
145                 InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName,
146                         physAddress);
147                 MDSALUtil.syncWrite(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, elanMacEntryId,
148                         macEntry);
149                 ElanInstance elanInstance = ElanUtils.getElanInstanceByName(elanName);
150                 WriteTransaction flowWritetx = elanServiceProvider.getBroker().newWriteOnlyTransaction();
151                 ElanUtils.setupMacFlows(elanInstance,
152                         elanServiceProvider.getInterfaceManager().getInterfaceInfo(interfaceName),
153                         elanInstance.getMacTimeout(), macAddress, flowWritetx);
154                 flowWritetx.submit();
155
156                 BigInteger dpId = elanServiceProvider.getInterfaceManager().getDpnForInterface(interfaceName);
157                 ElanL2GatewayUtils.scheduleAddDpnMacInExtDevices(elanInstance.getElanInstanceName(), dpId,
158                         Arrays.asList(physAddress));
159             } catch (Exception e) {
160                 logger.trace("Failed to decode packet: {}", e);
161             }
162         }
163
164     }
165
166     /*
167      * Though this method is a little costlier because it uses try-catch
168      * construct, it is used only in rare scenarios like MAC movement or invalid
169      * Static MAC having been added on a wrong ELAN.
170      */
171     private void tryAndRemoveInvalidMacEntry(String elanName, MacEntry macEntry) {
172         ElanInstance elanInfo = ElanUtils.getElanInstanceByName(elanName);
173         if (elanInfo == null) {
174             logger.warn(String.format("MAC %s is been added (either statically or dynamically) for an invalid Elan %s. "
175                     + "Manual cleanup may be necessary", macEntry.getMacAddress(), elanName));
176             return;
177         }
178
179         InterfaceInfo oldInterfaceLport = elanServiceProvider.getInterfaceManager()
180                 .getInterfaceInfo(macEntry.getInterface());
181         if (oldInterfaceLport == null) {
182             logger.warn(
183                     String.format(
184                             "MAC %s is been added (either statically or dynamically) on an invalid Logical Port %s. "
185                                     + "Manual cleanup may be necessary",
186                             macEntry.getMacAddress(), macEntry.getInterface()));
187             return;
188         }
189         WriteTransaction flowDeletetx = elanServiceProvider.getBroker().newWriteOnlyTransaction();
190         ElanUtils.deleteMacFlows(elanInfo, oldInterfaceLport, macEntry, flowDeletetx);
191         flowDeletetx.submit();
192         ElanL2GatewayUtils.removeMacsFromElanExternalDevices(elanInfo, Arrays.asList(macEntry.getMacAddress()));
193     }
194
195 }