Merge "Improve logging of unknown LISP control packets" into develop
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / LispSouthboundPlugin.java
1 /*
2  * Copyright (c) 2014 Contextream, Inc. 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
9 package org.opendaylight.lispflowmapping.southbound;
10
11 import java.io.IOException;
12 import java.net.DatagramPacket;
13 import java.net.DatagramSocket;
14 import java.net.InetAddress;
15 import java.net.InetSocketAddress;
16 import java.net.SocketException;
17 import java.net.SocketTimeoutException;
18 import java.nio.ByteBuffer;
19 import java.util.concurrent.Future;
20
21 import org.eclipse.osgi.framework.console.CommandProvider;
22 import org.opendaylight.controller.sal.binding.api.AbstractBindingAwareProvider;
23 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
24 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
25 import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
26 import org.opendaylight.lispflowmapping.implementation.serializer.MapNotifySerializer;
27 import org.opendaylight.lispflowmapping.implementation.serializer.MapReplySerializer;
28 import org.opendaylight.lispflowmapping.implementation.serializer.MapRequestSerializer;
29 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundService;
30 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispPlugin;
31 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispflowmappingService;
32 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.SendMapNotifyInput;
33 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.SendMapReplyInput;
34 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.SendMapRequestInput;
35 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.transportaddress.TransportAddress;
36 import org.opendaylight.yangtools.yang.common.RpcResult;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.FrameworkUtil;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.google.common.net.InetAddresses;
43
44 public class LispSouthboundPlugin extends AbstractBindingAwareProvider implements IConfigLispPlugin, CommandProvider, LispflowmappingService {
45     protected static final Logger logger = LoggerFactory.getLogger(LispSouthboundPlugin.class);
46
47     private static Object startLock = new Object();
48     private LispIoThread thread;
49     private LispSouthboundService lispSouthboundService;
50     private volatile DatagramSocket socket = null;
51     private final String MAP_NOTIFY = "MapNotify";
52     private final String MAP_REPlY = "MapReply";
53     private final String MAP_REQUEST = "MapRequest";
54     private volatile String bindingAddress = null;
55     private volatile boolean stillRunning = false;
56     private volatile boolean alreadyInit = false;
57
58     private void registerWithOSGIConsole() {
59         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
60         bundleContext.registerService(CommandProvider.class.getName(), this, null);
61         bundleContext.registerService(IConfigLispPlugin.class.getName(), this, null);
62     }
63
64     protected void stopImpl(BundleContext context) {
65         unloadActions();
66     }
67
68     private void unloadActions() {
69         if (thread != null) {
70             thread.stopRunning();
71         }
72         lispSouthboundService = null;
73         thread = null;
74         logger.info("LISP (RFC6830) Mapping Service is down!");
75         try {
76             Thread.sleep(1100);
77         } catch (InterruptedException e) {
78         }
79     }
80
81     public void destroy() {
82         unloadActions();
83     }
84
85     private class LispIoThread extends Thread {
86         private volatile boolean running;
87
88         public LispIoThread() {
89             super("Lisp Thread");
90             running = true;
91         }
92
93         @Override
94         public void run() {
95             stillRunning = true;
96
97             int lispPortNumber = LispMessage.PORT_NUM;
98             int lispReceiveTimeout = 1000;
99
100             logger.info("LISP (RFC6830) Mapping Service is running and listening on " + bindingAddress);
101             try {
102                 socket = new DatagramSocket(new InetSocketAddress(bindingAddress, lispPortNumber));
103                 socket.setSoTimeout(lispReceiveTimeout);
104             } catch (SocketException e) {
105                 logger.error("Cannot open socket on UDP port " + lispPortNumber, e);
106                 return;
107             }
108
109             while (running) {
110                 byte[] buffer = new byte[4096];
111                 DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
112                 try {
113                     socket.receive(packet);
114                     logger.trace("Received a packet!");
115                 } catch (SocketTimeoutException ste) {
116                     continue;
117                 } catch (IOException e) {
118                     logger.warn("IO Exception while trying to recieve packet", e);
119                 }
120                 logger.trace(String.format("Handling packet from {%s}:{%d} (len={%d})", packet.getAddress().getHostAddress(), packet.getPort(),
121                         packet.getLength()));
122
123                 try {
124                     lispSouthboundService.handlePacket(packet);
125                 } catch (Throwable t) {
126                     logger.warn("Error while handling packet", t);
127                 }
128             }
129
130             socket.close();
131             logger.trace("Socket closed");
132             stillRunning = false;
133         }
134
135         public void stopRunning() {
136             running = false;
137         }
138     }
139
140     public static String intToIpv4(int address) {
141         return ((address >> 24) & 0xff) + "." + //
142                 ((address >> 16) & 0xff) + "." + //
143                 ((address >> 8) & 0xff) + "." + //
144                 ((address >> 0) & 0xff);
145     }
146
147     public String getHelp() {
148         StringBuffer help = new StringBuffer();
149         help.append("---LISP Southbound Plugin---\n");
150         return help.toString();
151     }
152
153     private void startIOThread() {
154         thread = new LispIoThread();
155         logger.info("LISP (RFC6830) Mapping Service Southbound Plugin is up!");
156         thread.start();
157     }
158
159     public void onSessionInitiated(ProviderContext session) {
160         logger.info("LISP (RFC6830) Mapping Service is up!");
161         synchronized (startLock) {
162             if (!alreadyInit) {
163                 alreadyInit = true;
164                 lispSouthboundService = new LispSouthboundService();
165                 registerWithOSGIConsole();
166                 registerRPCs(session);
167                 logger.trace("Provider Session initialized");
168                 if (bindingAddress == null) {
169                     setLispAddress("0.0.0.0");
170                 }
171             }
172
173         }
174     }
175
176     private void registerRPCs(ProviderContext session) {
177         try {
178             lispSouthboundService.setNotificationProvider(session.getSALService(NotificationProviderService.class));
179             session.addRpcImplementation(LispflowmappingService.class, this);
180         } catch (Throwable t) {
181             logger.error(t.getMessage(), t);
182         }
183     }
184
185     private void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer, String packetType) {
186         DatagramPacket packet = new DatagramPacket(outBuffer.array(), outBuffer.limit());
187         packet.setPort(address.getPort().getValue());
188         InetAddress ip = InetAddresses.forString(address.getIpAddress().getIpv4Address().getValue());
189         packet.setAddress(ip);
190         try {
191             if (logger.isDebugEnabled()) {
192                 logger.trace("Sending " + packetType + " on port " + address.getPort().getValue() + " to address: " + ip);
193             }
194             socket.send(packet);
195         } catch (IOException e) {
196             logger.warn("Failed to send " + packetType, e);
197         }
198     }
199
200     public void setLispAddress(String address) {
201         synchronized (startLock) {
202             if (bindingAddress != null && bindingAddress.equals(address)) {
203                 logger.trace("configured lisp binding address didn't change.");
204             } else {
205                 String action = (bindingAddress == null ? "Setting" : "Resetting");
206                 logger.trace(action + " lisp binding address to: " + address);
207                 bindingAddress = address;
208                 if (thread != null) {
209                     thread.stopRunning();
210                     while (stillRunning) {
211                         try {
212                             Thread.sleep(500);
213                         } catch (InterruptedException e) {
214                         }
215                     }
216                 }
217                 startIOThread();
218             }
219         }
220     }
221
222     @Override
223     public Future<RpcResult<Void>> sendMapNotify(SendMapNotifyInput mapNotifyInput) {
224         logger.trace("sendMapNotify called!!");
225         if (mapNotifyInput != null) {
226             ByteBuffer outBuffer = MapNotifySerializer.getInstance().serialize(mapNotifyInput.getMapNotify());
227             handleSerializedLispBuffer(mapNotifyInput.getTransportAddress(), outBuffer, MAP_NOTIFY);
228         } else {
229             logger.warn("MapNotify was null");
230         }
231         return null;
232     }
233
234     @Override
235     public Future<RpcResult<Void>> sendMapReply(SendMapReplyInput mapReplyInput) {
236         logger.trace("sendMapReply called!!");
237         if (mapReplyInput != null) {
238             ByteBuffer outBuffer = MapReplySerializer.getInstance().serialize(mapReplyInput.getMapReply());
239             handleSerializedLispBuffer(mapReplyInput.getTransportAddress(), outBuffer, MAP_REPlY);
240         } else {
241             logger.warn("MapReply was null");
242         }
243         return null;
244     }
245
246     @Override
247     public Future<RpcResult<Void>> sendMapRequest(SendMapRequestInput mapRequestInput) {
248         logger.trace("sendMapRequest called!!");
249         if (mapRequestInput != null) {
250             ByteBuffer outBuffer = MapRequestSerializer.getInstance().serialize(mapRequestInput.getMapRequest());
251             handleSerializedLispBuffer(mapRequestInput.getTransportAddress(), outBuffer, MAP_REQUEST);
252         } else {
253             logger.debug("MapRequest was null");
254         }
255         return null;
256     }
257 }