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