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