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