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