Bug 5267 - Setting vlan id for termination end point not working
[vpnservice.git] / alivenessmonitor / alivenessmonitor-impl / src / main / java / org / opendaylight / vpnservice / alivenessmonitor / internal / AlivenessProtocolHandlerLLDP.java
1 /*
2  * Copyright (c) 2015 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.vpnservice.alivenessmonitor.internal;
9
10 import java.math.BigInteger;
11 import java.nio.charset.Charset;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.List;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.atomic.AtomicInteger;
17 import java.util.concurrent.Future;
18
19 import org.apache.commons.lang3.StringUtils;
20 import org.opendaylight.controller.liblldp.EtherTypes;
21 import org.opendaylight.controller.liblldp.LLDP;
22 import org.opendaylight.controller.liblldp.LLDPTLV;
23 import org.opendaylight.controller.liblldp.LLDPTLV.TLVType;
24 import org.opendaylight.controller.liblldp.Packet;
25 import org.opendaylight.controller.liblldp.PacketException;
26 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
27 import org.opendaylight.vpnservice.mdsalutil.ActionType;
28 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
29 import org.opendaylight.vpnservice.mdsalutil.MetaDataUtil;
30 import org.opendaylight.vpnservice.mdsalutil.packet.Ethernet;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.alivenessmonitor.rev150629.endpoint.EndpointType;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.alivenessmonitor.rev150629.endpoint.endpoint.type.Interface;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.alivenessmonitor.rev150629.monitor.configs.MonitoringInfo;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetDpidFromInterfaceInputBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetDpidFromInterfaceInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetDpidFromInterfaceOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetInterfaceFromIfIndexInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetInterfaceFromIfIndexInputBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetInterfaceFromIfIndexOutput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetPortFromInterfaceInputBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetPortFromInterfaceInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetPortFromInterfaceOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.OdlInterfaceRpcService;
50 import org.opendaylight.yangtools.yang.common.RpcResult;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 import com.google.common.base.Strings;
55
56 public class AlivenessProtocolHandlerLLDP extends AbstractAlivenessProtocolHandler {
57     private static final Logger LOG = LoggerFactory.getLogger(AlivenessProtocolHandlerLLDP.class);
58     private AtomicInteger packetId = new AtomicInteger(0);
59
60     public AlivenessProtocolHandlerLLDP(ServiceProvider serviceProvider) {
61         super(serviceProvider);
62     }
63
64     @Override
65     public Class<?> getPacketClass() {
66         return LLDP.class;
67     }
68
69     @Override
70     public String handlePacketIn(Packet protocolPacket, PacketReceived packetReceived) {
71         String sSourceDpnId = null;
72         String sPortNumber = null;
73         int nServiceId = -1;
74         int packetId = 0;
75
76         String sTmp = null;
77
78         byte lldpTlvTypeCur;
79
80         LLDP lldpPacket = (LLDP)protocolPacket;
81
82         LLDPTLV lldpTlvCur = lldpPacket.getSystemNameId();
83         if (lldpTlvCur != null) {
84             sSourceDpnId = new String(lldpTlvCur.getValue(), Charset.defaultCharset());
85         }
86
87         lldpTlvCur = lldpPacket.getPortId();
88         if (lldpTlvCur != null) {
89             sPortNumber = new String(lldpTlvCur.getValue(), Charset.defaultCharset());
90         }
91
92         for (LLDPTLV lldpTlv : lldpPacket.getOptionalTLVList()) {
93             lldpTlvTypeCur = lldpTlv.getType();
94
95             if (lldpTlvTypeCur == LLDPTLV.TLVType.SystemName.getValue()) {
96                 sSourceDpnId = new String(lldpTlvCur.getValue(), Charset.defaultCharset());
97             }
98         }
99
100         for (LLDPTLV lldpTlv : lldpPacket.getCustomTlvList()) {
101             lldpTlvTypeCur = lldpTlv.getType();
102
103             if (lldpTlvTypeCur == LLDPTLV.TLVType.Custom.getValue()) {
104                 sTmp = new String(lldpTlv.getValue());
105                 nServiceId = 0;
106             }
107         }
108
109         String interfaceName = null;
110
111         //TODO: Check if the below fields are required
112         if (!Strings.isNullOrEmpty(sTmp) && sTmp.contains("#")) {
113             String[] asTmp = sTmp.split("#");
114             interfaceName = asTmp[0];
115             packetId = Integer.parseInt(asTmp[1]);
116             LOG.debug("Custom LLDP Value on received packet: " + sTmp);
117         }
118
119         if(!Strings.isNullOrEmpty(interfaceName)) {
120             String monitorKey = new StringBuilder().append(interfaceName).append(EtherTypes.LLDP).toString();
121             return monitorKey;
122         } else {
123             LOG.debug("No associated interface found to handle received LLDP Packet");
124         }
125         return null;
126     }
127
128     @Override
129     public void sendPacketOut(MonitoringInfo monitorInfo) {
130         String sourceInterface;
131
132         EndpointType source = monitorInfo.getSource().getEndpointType();
133         if( source instanceof Interface) {
134             Interface intf = (Interface)source;
135             sourceInterface = intf.getInterfaceName();
136         } else {
137             LOG.warn("Invalid source endpoint. Could not retrieve source interface to send LLDP Packet");
138             return;
139         }
140
141         //Get Mac Address for the source interface
142         byte[] sourceMac = getMacAddress(sourceInterface);
143         if(sourceMac == null) {
144             LOG.error("Could not read mac address for the source interface {} from the Inventory. "
145                     + "LLDP packet cannot be send.", sourceInterface);
146             return;
147         }
148
149         OdlInterfaceRpcService interfaceService = serviceProvider.getInterfaceManager();
150
151         long nodeId = -1, portNum = -1;
152         try {
153             GetPortFromInterfaceInput input = new GetPortFromInterfaceInputBuilder().setIntfName(sourceInterface).build();
154             Future<RpcResult<GetPortFromInterfaceOutput>> portOutput = interfaceService.getPortFromInterface(input);
155             RpcResult<GetPortFromInterfaceOutput> result = portOutput.get();
156             if(result.isSuccessful()) {
157                 GetPortFromInterfaceOutput output = result.getResult();
158                 nodeId = output.getDpid().longValue();
159                 portNum = output.getPortno();
160             } else {
161                 LOG.error("Could not retrieve port details for interface {}", sourceInterface);
162                 return;
163             }
164         }catch(InterruptedException | ExecutionException e) {
165             LOG.error("Failed to retrieve interface service RPC Result ", e);
166             return;
167         }
168
169         Ethernet ethenetLLDPPacket = makeLLDPPacket(Long.toString(nodeId), portNum, 0, sourceMac, sourceInterface);
170
171         try {
172             List<ActionInfo> actions = getInterfaceActions(sourceInterface, portNum);
173             if(actions.isEmpty()) {
174                 LOG.error("No interface actions to send packet out over interface {}", sourceInterface);
175                 return;
176             }
177             TransmitPacketInput transmitPacketInput = MDSALUtil.getPacketOut(actions,
178                     ethenetLLDPPacket.serialize(), nodeId, MDSALUtil.getNodeConnRef(BigInteger.valueOf(nodeId), "0xfffffffd"));
179             serviceProvider.getPacketProcessingService().transmitPacket(transmitPacketInput);
180         } catch (Exception  e) {
181             LOG.error("Error while sending LLDP Packet", e);
182         }
183     }
184
185     private List<ActionInfo> getInterfaceActions(String interfaceName, long portNum) throws InterruptedException, ExecutionException {
186         Class<? extends InterfaceType> intfType;
187         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface interfaceInfo =
188                                                                                                      getInterfaceFromConfigDS(interfaceName);
189         if(interfaceInfo != null) {
190             intfType = interfaceInfo.getType();
191         } else {
192             LOG.error("Could not retrieve port type for interface {} to construct actions", interfaceName);
193             return Collections.emptyList();
194         }
195
196         List<ActionInfo> actionInfos  = new ArrayList<ActionInfo>();
197
198         if(Tunnel.class.equals(intfType)) {
199             actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[] {
200                     BigInteger.valueOf(0x08000000)}));
201         }
202         actionInfos.add(new ActionInfo(ActionType.output, new String[] { Long.toString(portNum) }));
203         return actionInfos;
204     }
205
206     private static LLDPTLV buildLLDTLV(LLDPTLV.TLVType tlvType,byte[] abyTLV) {
207         return new LLDPTLV().setType(tlvType.getValue()).setLength((short) abyTLV.length).setValue(abyTLV);
208     }
209
210     private int getPacketId() {
211         int id = packetId.incrementAndGet();
212         if(id > 16000) {
213             LOG.debug("Resetting the LLDP Packet Id counter");
214             packetId.set(0);
215         }
216
217         return id;
218     }
219
220     public Ethernet makeLLDPPacket(String nodeId,
221             long portNum, int serviceId, byte[] srcMac, String sourceInterface) {
222
223         // Create LLDP TTL TLV
224         LLDPTLV lldpTlvTTL = buildLLDTLV(LLDPTLV.TLVType.TTL, new byte[] { (byte) 0, (byte) 120 });
225
226         LLDPTLV lldpTlvChassisId = buildLLDTLV(LLDPTLV.TLVType.ChassisID, LLDPTLV.createChassisIDTLVValue(colonize(StringUtils
227                 .leftPad(Long.toHexString(MDSALUtil.getDpnIdFromNodeName(nodeId).longValue()), 16,
228                         "0"))));
229         LLDPTLV lldpTlvSystemName = buildLLDTLV(TLVType.SystemName, LLDPTLV.createSystemNameTLVValue(nodeId));
230
231         LLDPTLV lldpTlvPortId = buildLLDTLV(TLVType.PortID, LLDPTLV.createPortIDTLVValue(
232                 Long.toHexString(portNum)));
233
234         String customValue = sourceInterface + "#" + getPacketId();
235
236         LOG.debug("Sending LLDP packet, custome value " + customValue);
237
238         LLDPTLV lldpTlvCustom = buildLLDTLV(TLVType.Custom, customValue.getBytes());
239
240         List<LLDPTLV> lstLLDPTLVCustom = new ArrayList<>();
241         lstLLDPTLVCustom.add(lldpTlvCustom);
242
243         LLDP lldpDiscoveryPacket = new LLDP();
244         lldpDiscoveryPacket.setChassisId(lldpTlvChassisId)
245                            .setPortId(lldpTlvPortId)
246                            .setTtl(lldpTlvTTL)
247                            .setSystemNameId(lldpTlvSystemName)
248                            .setOptionalTLVList(lstLLDPTLVCustom);
249
250         byte[] destMac = LLDP.LLDPMulticastMac;
251
252         Ethernet ethernetPacket = new Ethernet();
253         ethernetPacket.setSourceMACAddress(srcMac)
254                       .setDestinationMACAddress(destMac)
255                       .setEtherType(EtherTypes.LLDP.shortValue())
256                       .setPayload(lldpDiscoveryPacket);
257
258         return ethernetPacket;
259     }
260
261     private String colonize(String orig) {
262         return orig.replaceAll("(?<=..)(..)", ":$1");
263     }
264
265     @Override
266     public String getUniqueMonitoringKey(MonitoringInfo monitorInfo) {
267         String interfaceName = getInterfaceName(monitorInfo.getSource().getEndpointType());
268         return new StringBuilder().append(interfaceName).append(EtherTypes.LLDP).toString();
269     }
270
271     private String getInterfaceName(EndpointType endpoint) {
272         String interfaceName = null;
273         if(endpoint instanceof Interface) {
274             interfaceName = ((Interface)endpoint).getInterfaceName();
275         }
276         return interfaceName;
277     }
278
279 }