Fix: Switch manager should clean the nodeconnector info when a switch disconnects
[controller.git] / opendaylight / forwarding / staticrouting / src / main / java / org / opendaylight / controller / forwarding / staticrouting / internal / StaticRoutingImplementation.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.controller.forwarding.staticrouting.internal;
11
12 import java.io.FileNotFoundException;
13 import java.io.IOException;
14 import java.io.ObjectInputStream;
15 import java.net.Inet4Address;
16 import java.net.InetAddress;
17 import java.nio.ByteBuffer;
18 import java.util.Collections;
19 import java.util.Date;
20 import java.util.Dictionary;
21 import java.util.EnumSet;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.Timer;
26 import java.util.TimerTask;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ConcurrentMap;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.Future;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 import org.apache.felix.dm.Component;
37 import org.opendaylight.controller.clustering.services.CacheConfigException;
38 import org.opendaylight.controller.clustering.services.CacheExistException;
39 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
40 import org.opendaylight.controller.clustering.services.IClusterServices;
41 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
42 import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting;
43 import org.opendaylight.controller.forwarding.staticrouting.IStaticRoutingAware;
44 import org.opendaylight.controller.forwarding.staticrouting.StaticRoute;
45 import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig;
46 import org.opendaylight.controller.hosttracker.IfIptoHost;
47 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
48 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
49 import org.opendaylight.controller.sal.utils.GlobalConstants;
50 import org.opendaylight.controller.sal.utils.IObjectReader;
51 import org.opendaylight.controller.sal.utils.ObjectReader;
52 import org.opendaylight.controller.sal.utils.ObjectWriter;
53 import org.opendaylight.controller.sal.utils.Status;
54 import org.opendaylight.controller.sal.utils.StatusCode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Static Routing feature provides the bridge between SDN and Non-SDN networks.
60  */
61 public class StaticRoutingImplementation implements IfNewHostNotify,
62         IForwardingStaticRouting, IObjectReader, IConfigurationContainerAware {
63     private static Logger log = LoggerFactory
64             .getLogger(StaticRoutingImplementation.class);
65     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
66     private static final String SAVE = "Save";
67     ConcurrentMap<String, StaticRoute> staticRoutes;
68     ConcurrentMap<String, StaticRouteConfig> staticRouteConfigs;
69     private IfIptoHost hostTracker;
70     private Timer gatewayProbeTimer;
71     private String staticRoutesFileName = null;
72     private IClusterContainerServices clusterContainerService = null;
73     private Set<IStaticRoutingAware> staticRoutingAware = Collections
74             .synchronizedSet(new HashSet<IStaticRoutingAware>());
75     private ExecutorService executor;
76
77     void setStaticRoutingAware(IStaticRoutingAware s) {
78         if (this.staticRoutingAware != null) {
79             this.staticRoutingAware.add(s);
80         }
81     }
82
83     void unsetStaticRoutingAware(IStaticRoutingAware s) {
84         if (this.staticRoutingAware != null) {
85             this.staticRoutingAware.remove(s);
86         }
87     }
88
89     public void setHostTracker(IfIptoHost hostTracker) {
90         log.debug("Setting HostTracker");
91         this.hostTracker = hostTracker;
92     }
93
94     public void unsetHostTracker(IfIptoHost hostTracker) {
95         if (this.hostTracker == hostTracker) {
96             this.hostTracker = null;
97         }
98     }
99
100     public ConcurrentMap<String, StaticRouteConfig> getStaticRouteConfigs() {
101         return staticRouteConfigs;
102     }
103
104     public void setStaticRouteConfigs(
105             ConcurrentMap<String, StaticRouteConfig> staticRouteConfigs) {
106         this.staticRouteConfigs = staticRouteConfigs;
107     }
108
109     @Override
110     public Object readObject(ObjectInputStream ois)
111             throws FileNotFoundException, IOException, ClassNotFoundException {
112         // Perform the class deserialization locally, from inside the package
113         // where the class is defined
114         return ois.readObject();
115     }
116
117     @SuppressWarnings("unchecked")
118     private void loadConfiguration() {
119         ObjectReader objReader = new ObjectReader();
120         ConcurrentMap<String, StaticRouteConfig> confList = (ConcurrentMap<String, StaticRouteConfig>) objReader
121                 .read(this, staticRoutesFileName);
122
123         if (confList == null) {
124             return;
125         }
126
127         for (StaticRouteConfig conf : confList.values()) {
128             addStaticRoute(conf);
129         }
130     }
131
132
133     private Status saveConfig() {
134         return saveConfigInternal();
135     }
136
137     public Status saveConfigInternal() {
138         Status status;
139         ObjectWriter objWriter = new ObjectWriter();
140
141         status = objWriter.write(
142                 new ConcurrentHashMap<String, StaticRouteConfig>(
143                         staticRouteConfigs), staticRoutesFileName);
144
145         if (status.isSuccess()) {
146             return status;
147         } else {
148             return new Status(StatusCode.INTERNALERROR, "Save failed");
149         }
150     }
151
152     @SuppressWarnings("deprecation")
153         private void allocateCaches() {
154         if (this.clusterContainerService == null) {
155             log
156                     .info("un-initialized clusterContainerService, can't create cache");
157             return;
158         }
159
160         try {
161             clusterContainerService.createCache(
162                     "forwarding.staticrouting.routes", EnumSet
163                             .of(IClusterServices.cacheMode.TRANSACTIONAL));
164             clusterContainerService.createCache(
165                     "forwarding.staticrouting.configs", EnumSet
166                             .of(IClusterServices.cacheMode.TRANSACTIONAL));
167         } catch (CacheExistException cee) {
168             log
169                     .error("\nCache already exists - destroy and recreate if needed");
170         } catch (CacheConfigException cce) {
171             log.error("\nCache configuration invalid - check cache mode");
172         }
173     }
174
175     @SuppressWarnings({ "unchecked", "deprecation" })
176     private void retrieveCaches() {
177         if (this.clusterContainerService == null) {
178             log
179                     .info("un-initialized clusterContainerService, can't retrieve cache");
180             return;
181         }
182
183         staticRoutes = (ConcurrentMap<String, StaticRoute>) clusterContainerService
184                 .getCache("forwarding.staticrouting.routes");
185         if (staticRoutes == null) {
186             log.error("\nFailed to get rulesDB handle");
187         }
188
189         staticRouteConfigs = (ConcurrentMap<String, StaticRouteConfig>) clusterContainerService
190                 .getCache("forwarding.staticrouting.configs");
191         if (staticRouteConfigs == null) {
192             log.error("\nFailed to get rulesDB handle");
193         }
194     }
195
196     private void notifyStaticRouteUpdate(StaticRoute s, boolean update) {
197         if (this.staticRoutingAware != null) {
198             log.info("Invoking StaticRoutingAware listeners");
199             synchronized (this.staticRoutingAware) {
200                 for (IStaticRoutingAware ra : this.staticRoutingAware) {
201                     try {
202                         ra.staticRouteUpdate(s, update);
203                     } catch (Exception e) {
204                         log.error("",e);
205                     }
206                 }
207             }
208         }
209     }
210
211     private class NotifyStaticRouteWorker implements Callable<Object> {
212         private StaticRoute staticRoute;
213         private boolean added;
214
215         public NotifyStaticRouteWorker(StaticRoute s, boolean update) {
216             this.staticRoute = s;
217             this.added = update;
218         }
219
220         @Override
221         public Object call() throws Exception {
222             if (!added
223                     || (staticRoute.getType() == StaticRoute.NextHopType.SWITCHPORT)) {
224                 notifyStaticRouteUpdate(staticRoute, added);
225             } else {
226                 InetAddress nh = staticRoute.getNextHopAddress();
227                 HostNodeConnector host = hostTracker.hostQuery(nh);
228                 if (host == null) {
229                     log.debug("Next hop {}  is not present, try to discover it", nh.getHostAddress());
230                     Future<HostNodeConnector> future = hostTracker.discoverHost(nh);
231                     if (future != null) {
232                         try {
233                             host = future.get();
234                         } catch (Exception e) {
235                             log.error("", e);
236                         }
237                     }
238                 }
239                 if (host != null) {
240                     log.debug("Next hop {} is found", nh.getHostAddress());
241                     staticRoute.setHost(host);
242                     notifyStaticRouteUpdate(staticRoute, added);
243                 } else {
244                     log.debug("Next hop {}  is still not present, try again later", nh.getHostAddress());
245                 }
246             }
247             return null;
248         }
249     }
250
251     private void checkAndUpdateListeners(StaticRoute staticRoute, boolean added) {
252         NotifyStaticRouteWorker worker = new NotifyStaticRouteWorker(staticRoute, added);
253         try {
254             executor.submit(worker);
255         } catch (Exception e) {
256             log.error("got Exception ", e);
257         }
258     }
259
260     private void notifyHostUpdate(HostNodeConnector host, boolean added) {
261         if (host == null)
262             return;
263         for (StaticRoute s : staticRoutes.values()) {
264             if (s.getType() == StaticRoute.NextHopType.SWITCHPORT)
265                 continue;
266             if (s.getNextHopAddress().equals(host.getNetworkAddress())) {
267                 if (added) {
268                     s.setHost(host);
269                 } else {
270                     s.setHost(null);
271                 }
272                 notifyStaticRouteUpdate(s, added);
273             }
274         }
275     }
276
277     @Override
278     public void notifyHTClient(HostNodeConnector host) {
279         notifyHostUpdate(host, true);
280     }
281
282     @Override
283     public void notifyHTClientHostRemoved(HostNodeConnector host) {
284         notifyHostUpdate(host, false);
285     }
286
287     public boolean isIPv4AddressValid(String cidr) {
288         if (cidr == null)
289             return false;
290
291         String values[] = cidr.split("/");
292         Pattern ipv4Pattern = Pattern
293                 .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
294         Matcher mm = ipv4Pattern.matcher(values[0]);
295         if (!mm.matches()) {
296             log.debug("IPv4 source address {} is not valid", cidr);
297             return false;
298         }
299         if (values.length >= 2) {
300             int prefix = Integer.valueOf(values[1]);
301             if ((prefix < 0) || (prefix > 32)) {
302                 log.debug("prefix {} is not valid", prefix);
303                 return false;
304             }
305         }
306         return true;
307     }
308
309     public static short getUnsignedByte(ByteBuffer bb, int position) {
310         return ((short) (bb.get(position) & (short) 0xff));
311     }
312
313     public static int compareByteBuffers(ByteBuffer buf1, ByteBuffer buf2) {
314         for (int i = 0; i < buf1.array().length; i++) {
315             if (getUnsignedByte(buf1, i) > getUnsignedByte(buf2, i)) {
316                 return 1;
317             } else if (getUnsignedByte(buf1, i) < getUnsignedByte(buf2, i)) {
318                 return -1;
319             }
320         }
321
322         return 0;
323     }
324
325     public StaticRoute getBestMatchStaticRoute(InetAddress ipAddress) {
326         ByteBuffer bblongestPrefix = null;
327         try {
328             bblongestPrefix = ByteBuffer.wrap(InetAddress.getByName("0.0.0.0")
329                     .getAddress());
330         } catch (Exception e) {
331             return null;
332         }
333
334         if (staticRoutes == null) {
335             return null;
336         }
337
338         StaticRoute longestPrefixRoute = null;
339         for (StaticRoute s : staticRoutes.values()) {
340             InetAddress prefix = s.longestPrefixMatch(ipAddress);
341             if ((prefix != null) && (prefix instanceof Inet4Address)) {
342                 ByteBuffer bbtmp = ByteBuffer.wrap(prefix.getAddress());
343                 if (compareByteBuffers(bbtmp, bblongestPrefix) > 0) {
344                     bblongestPrefix = bbtmp;
345                     longestPrefixRoute = s;
346                 }
347             }
348         }
349         return longestPrefixRoute;
350     }
351
352     public Status addStaticRoute(StaticRouteConfig config) {
353         Status status;
354
355         status = config.isValid();
356         if (!status.isSuccess()) {
357             return status;
358         }
359         if (staticRouteConfigs.get(config.getName()) != null) {
360                 return new Status(StatusCode.CONFLICT,
361                                 "A valid Static Route configuration with this name " +
362                                                 "already exists. Please use a different name");
363         }
364         for (StaticRouteConfig s : staticRouteConfigs.values()) {
365             if (s.equals(config)) {
366                 return new Status(StatusCode.CONFLICT,
367                                 "This conflicts with an existing Static Route " +
368                                         "Configuration. Please check the configuration " +
369                                                 "and try again");
370             }
371         }
372
373         staticRouteConfigs.put(config.getName(), config);
374         StaticRoute sRoute = new StaticRoute(config);
375         staticRoutes.put(config.getName(), sRoute);
376         checkAndUpdateListeners(sRoute, true);
377         return status;
378     }
379
380     public Status removeStaticRoute(String name) {
381         staticRouteConfigs.remove(name);
382         StaticRoute sRoute = staticRoutes.remove(name);
383         if (sRoute != null) {
384             checkAndUpdateListeners(sRoute, false);
385             return new Status(StatusCode.SUCCESS, null);
386         }
387         return new Status(StatusCode.NOTFOUND,
388                         "Static Route with name " + name + " is not found");
389     }
390
391     void setClusterContainerService(IClusterContainerServices s) {
392         log.debug("Cluster Service set");
393         this.clusterContainerService = s;
394     }
395
396     void unsetClusterContainerService(IClusterContainerServices s) {
397         if (this.clusterContainerService == s) {
398             log.debug("Cluster Service removed!");
399             this.clusterContainerService = null;
400         }
401     }
402
403     /**
404      * Function called by the dependency manager when all the required
405      * dependencies are satisfied
406      *
407      */
408     void init(Component c) {
409         String containerName = null;
410         Dictionary props = c.getServiceProperties();
411         if (props != null) {
412             containerName = (String) props.get("containerName");
413         } else {
414             // In the Global instance case the containerName is empty
415             containerName = "";
416         }
417
418         staticRoutesFileName = ROOT + "staticRouting_" + containerName
419                 + ".conf";
420
421         log.debug("forwarding.staticrouting starting on container {}",
422                   containerName);
423         //staticRoutes = new ConcurrentHashMap<String, StaticRoute>();
424         allocateCaches();
425         retrieveCaches();
426         this.executor = Executors.newFixedThreadPool(1);
427         if (staticRouteConfigs.isEmpty())
428             loadConfiguration();
429
430         /*
431          *  Slow probe to identify any gateway that might have silently appeared
432          *  after the Static Routing Configuration.
433          */
434         gatewayProbeTimer = new Timer();
435         gatewayProbeTimer.schedule(new TimerTask() {
436             @Override
437             public void run() {
438                 for (StaticRoute s : staticRoutes.values()) {
439                     if ((s.getType() == StaticRoute.NextHopType.IPADDRESS)
440                             && s.getHost() == null) {
441                         checkAndUpdateListeners(s, true);
442                     }
443                 }
444             }
445         }, 60 * 1000, 60 * 1000);
446     }
447
448     /**
449      * Function called by the dependency manager when at least one
450      * dependency become unsatisfied or when the component is shutting
451      * down because for example bundle is being stopped.
452      *
453      */
454     void destroy() {
455         log.debug("Destroy all the Static Routing Rules given we are "
456                 + "shutting down");
457
458         gatewayProbeTimer.cancel();
459
460         // Clear the listener so to be ready in next life
461         this.staticRoutingAware.clear();
462     }
463
464     /**
465      * Function called by dependency manager after "init ()" is called
466      * and after the services provided by the class are registered in
467      * the service registry
468      *
469      */
470     void start() {
471     }
472
473     /**
474      * Function called by the dependency manager before the services
475      * exported by the component are unregistered, this will be
476      * followed by a "destroy ()" calls
477      *
478      */
479     void stop() {
480         executor.shutdown();
481     }
482
483     @Override
484     public Status saveConfiguration() {
485         return this.saveConfig();
486     }
487
488 }