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