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