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