started non proxy CXTMAP-66: #close
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / LispSouthboundPlugin.java
1 /*
2  * Copyright (c) 2013 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.warn("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.debug("Received a packet!");
112                 } catch (SocketTimeoutException ste) {
113                     continue;
114                 } catch (IOException e) {
115                     logger.error("IO Exception while trying to recieve packet", e);
116                 }
117                 logger.debug("Handling packet from {}:{} (len={})", packet.getAddress().getHostAddress(), packet.getPort(), packet.getLength());
118
119                 try {
120                     lispSouthboundService.handlePacket(packet);
121                 } catch (Throwable t) {
122                     logger.error("Error while handling packet", t);
123                 }
124             }
125
126             socket.close();
127             logger.info("Socket closed");
128             stillRunning = false;
129         }
130
131         public void stopRunning() {
132             running = false;
133         }
134     }
135
136     public static String intToIpv4(int address) {
137         return ((address >> 24) & 0xff) + "." + //
138                 ((address >> 16) & 0xff) + "." + //
139                 ((address >> 8) & 0xff) + "." + //
140                 ((address >> 0) & 0xff);
141     }
142
143     public String getHelp() {
144         StringBuffer help = new StringBuffer();
145         help.append("---LISP Southbound Plugin---\n");
146         return help.toString();
147     }
148
149     private void startIOThread() {
150         thread = new LispIoThread();
151         logger.info("LISP (RFC6830) Mapping Service Southbound Plugin is up!");
152         thread.start();
153     }
154
155     public void onSessionInitiated(ProviderContext session) {
156         logger.info("LISP (RFC6830) Mapping Service is up!");
157         synchronized (startLock) {
158             if (!alreadyInit) {
159                 alreadyInit = true;
160                 lispSouthboundService = new LispSouthboundService();
161                 registerWithOSGIConsole();
162                 registerRPCs(session);
163                 logger.debug("Provider Session initialized");
164                 if (bindingAddress == null) {
165                     setLispAddress("0.0.0.0");
166                 }
167             }
168
169         }
170     }
171
172     private void registerRPCs(ProviderContext session) {
173         try {
174             lispSouthboundService.setNotificationProvider(session.getSALService(NotificationProviderService.class));
175             session.addRpcImplementation(ILispSouthboundPlugin.class, this);
176         } catch (Throwable t) {
177             logger.error(t.getMessage(), t);
178         }
179     }
180
181     public Future<RpcResult<Void>> handleMapNotify(MapNotify mapNotify, InetAddress address) {
182         logger.trace("handleMapNotify called!!");
183         if (mapNotify != null) {
184             ByteBuffer outBuffer = MapNotifySerializer.getInstance().serialize(mapNotify);
185             handleSerializedLispBuffer(address, outBuffer, MAP_NOTIFY);
186         } else {
187             logger.debug("MapNotify was null");
188         }
189         return null;
190     }
191
192     private void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer, String packetType) {
193         DatagramPacket packet = new DatagramPacket(outBuffer.array(), outBuffer.limit());
194         packet.setPort(LispMessage.PORT_NUM);
195         packet.setAddress(address);
196         try {
197             if (logger.isDebugEnabled()) {
198                 logger.debug("Sending " + packetType + " on port " + LispMessage.PORT_NUM + " to address: " + address);
199             }
200             socket.send(packet);
201         } catch (IOException e) {
202             logger.error("Failed to send " + packetType, e);
203         }
204     }
205
206     public Future<RpcResult<Void>> handleMapReply(MapReply mapReply, InetAddress address) {
207         logger.trace("handleMapReply called!!");
208         if (mapReply != null) {
209             ByteBuffer outBuffer = MapReplySerializer.getInstance().serialize(mapReply);
210             handleSerializedLispBuffer(address, outBuffer, MAP_REPlY);
211         } else {
212             logger.debug("MapReply was null");
213         }
214         return null;
215     }
216
217     public Future<RpcResult<Void>> handleMapRequest(MapRequest mapRequest, InetAddress address) {
218         logger.trace("handleMapRequest called!!");
219         if (mapRequest != null) {
220             ByteBuffer outBuffer = MapRequestSerializer.getInstance().serialize(mapRequest);
221             handleSerializedLispBuffer(address, outBuffer, MAP_REQUEST);
222         } else {
223             logger.debug("MapRequest was null");
224         }
225         return null;
226     }
227
228     public void setLispAddress(String address) {
229         synchronized (startLock) {
230             if (bindingAddress != null && bindingAddress.equals(address)) {
231                 logger.debug("configured lisp binding address didn't change.");
232             } else {
233                 String action = (bindingAddress == null ? "Setting" : "Resetting");
234                 logger.info(action + " lisp binding address to: " + address);
235                 bindingAddress = address;
236                 if (thread != null) {
237                     thread.stopRunning();
238                     while (stillRunning) {
239                         try {
240                             Thread.sleep(500);
241                         } catch (InterruptedException e) {
242                             e.printStackTrace();
243                         }
244                     }
245                 }
246                 startIOThread();
247             }
248         }
249     }
250 }