3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
10 package org.opendaylight.controller.forwarding.staticrouting.internal;
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;
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;
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;
59 * Static Routing feature provides the bridge between SDN and Non-SDN networks.
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 ConcurrentMap<String, StaticRoute> staticRoutes;
67 ConcurrentMap<String, StaticRouteConfig> staticRouteConfigs;
68 private IfIptoHost hostTracker;
69 private Timer gatewayProbeTimer;
70 private String staticRoutesFileName = null;
71 private IClusterContainerServices clusterContainerService = null;
72 private Set<IStaticRoutingAware> staticRoutingAware = Collections
73 .synchronizedSet(new HashSet<IStaticRoutingAware>());
74 private ExecutorService executor;
76 void setStaticRoutingAware(IStaticRoutingAware s) {
77 if (this.staticRoutingAware != null) {
78 this.staticRoutingAware.add(s);
82 void unsetStaticRoutingAware(IStaticRoutingAware s) {
83 if (this.staticRoutingAware != null) {
84 this.staticRoutingAware.remove(s);
88 public void setHostTracker(IfIptoHost hostTracker) {
89 log.debug("Setting HostTracker");
90 this.hostTracker = hostTracker;
93 public void unsetHostTracker(IfIptoHost hostTracker) {
94 if (this.hostTracker == hostTracker) {
95 this.hostTracker = null;
100 public ConcurrentMap<String, StaticRouteConfig> getStaticRouteConfigs() {
101 return staticRouteConfigs;
104 public void setStaticRouteConfigs(
105 ConcurrentMap<String, StaticRouteConfig> staticRouteConfigs) {
106 this.staticRouteConfigs = staticRouteConfigs;
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();
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);
123 if (confList == null) {
127 for (StaticRouteConfig conf : confList.values()) {
128 addStaticRoute(conf);
133 private Status saveConfig() {
134 return saveConfigInternal();
137 public Status saveConfigInternal() {
139 ObjectWriter objWriter = new ObjectWriter();
141 status = objWriter.write(
142 new ConcurrentHashMap<String, StaticRouteConfig>(
143 staticRouteConfigs), staticRoutesFileName);
145 if (status.isSuccess()) {
148 return new Status(StatusCode.INTERNALERROR, "Save failed");
152 @SuppressWarnings("deprecation")
153 private void allocateCaches() {
154 if (this.clusterContainerService == null) {
156 .info("un-initialized clusterContainerService, can't create cache");
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) {
169 .error("\nCache already exists - destroy and recreate if needed");
170 } catch (CacheConfigException cce) {
171 log.error("\nCache configuration invalid - check cache mode");
175 @SuppressWarnings({ "unchecked", "deprecation" })
176 private void retrieveCaches() {
177 if (this.clusterContainerService == null) {
179 .info("un-initialized clusterContainerService, can't retrieve cache");
183 staticRoutes = (ConcurrentMap<String, StaticRoute>) clusterContainerService
184 .getCache("forwarding.staticrouting.routes");
185 if (staticRoutes == null) {
186 log.error("\nFailed to get rulesDB handle");
189 staticRouteConfigs = (ConcurrentMap<String, StaticRouteConfig>) clusterContainerService
190 .getCache("forwarding.staticrouting.configs");
191 if (staticRouteConfigs == null) {
192 log.error("\nFailed to get rulesDB handle");
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) {
202 ra.staticRouteUpdate(s, update);
203 } catch (Exception e) {
211 private class NotifyStaticRouteWorker implements Callable<Object> {
212 private StaticRoute staticRoute;
213 private boolean added;
215 public NotifyStaticRouteWorker(StaticRoute s, boolean update) {
216 this.staticRoute = s;
221 public Object call() throws Exception {
223 || (staticRoute.getType() == StaticRoute.NextHopType.SWITCHPORT)) {
224 notifyStaticRouteUpdate(staticRoute, added);
226 InetAddress nh = staticRoute.getNextHopAddress();
227 HostNodeConnector host = hostTracker.hostQuery(nh);
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) {
234 } catch (InterruptedException ioe) {
235 log.trace("Thread interrupted {}", ioe);
236 } catch (Exception e) {
242 log.debug("Next hop {} is found", nh.getHostAddress());
243 staticRoute.setHost(host);
244 notifyStaticRouteUpdate(staticRoute, added);
246 log.debug("Next hop {} is still not present, try again later", nh.getHostAddress());
253 private void checkAndUpdateListeners(StaticRoute staticRoute, boolean added) {
254 NotifyStaticRouteWorker worker = new NotifyStaticRouteWorker(staticRoute, added);
256 executor.submit(worker);
257 } catch (Exception e) {
258 log.error("got Exception ", e);
262 private void notifyHostUpdate(HostNodeConnector host, boolean added) {
266 for (StaticRoute s : staticRoutes.values()) {
267 if (s.getType() == StaticRoute.NextHopType.SWITCHPORT) {
270 if (s.getNextHopAddress().equals(host.getNetworkAddress())) {
276 notifyStaticRouteUpdate(s, added);
282 public void notifyHTClient(HostNodeConnector host) {
283 notifyHostUpdate(host, true);
287 public void notifyHTClientHostRemoved(HostNodeConnector host) {
288 notifyHostUpdate(host, false);
291 public boolean isIPv4AddressValid(String cidr) {
296 String values[] = cidr.split("/");
297 Pattern ipv4Pattern = Pattern
298 .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
299 Matcher mm = ipv4Pattern.matcher(values[0]);
301 log.debug("IPv4 source address {} is not valid", cidr);
304 if (values.length >= 2) {
305 int prefix = Integer.valueOf(values[1]);
306 if ((prefix < 0) || (prefix > 32)) {
307 log.debug("prefix {} is not valid", prefix);
314 public static short getUnsignedByte(ByteBuffer bb, int position) {
315 return ((short) (bb.get(position) & (short) 0xff));
318 public static int compareByteBuffers(ByteBuffer buf1, ByteBuffer buf2) {
319 for (int i = 0; i < buf1.array().length; i++) {
320 if (getUnsignedByte(buf1, i) > getUnsignedByte(buf2, i)) {
322 } else if (getUnsignedByte(buf1, i) < getUnsignedByte(buf2, i)) {
331 public StaticRoute getBestMatchStaticRoute(InetAddress ipAddress) {
332 ByteBuffer bblongestPrefix = null;
334 bblongestPrefix = ByteBuffer.wrap(InetAddress.getByName("0.0.0.0")
336 } catch (Exception e) {
340 if (staticRoutes == null) {
344 StaticRoute longestPrefixRoute = null;
345 for (StaticRoute s : staticRoutes.values()) {
346 InetAddress prefix = s.longestPrefixMatch(ipAddress);
347 if ((prefix != null) && (prefix instanceof Inet4Address)) {
348 ByteBuffer bbtmp = ByteBuffer.wrap(prefix.getAddress());
349 if (compareByteBuffers(bbtmp, bblongestPrefix) > 0) {
350 bblongestPrefix = bbtmp;
351 longestPrefixRoute = s;
355 return longestPrefixRoute;
359 public Status addStaticRoute(StaticRouteConfig config) {
360 Status status = config.isValid();
361 if (!status.isSuccess()) {
364 if (staticRouteConfigs.get(config.getName()) != null) {
365 return new Status(StatusCode.CONFLICT,
366 "A valid Static Route configuration with this name " +
367 "already exists. Please use a different name");
371 StaticRoute sRoute = new StaticRoute(config);
373 for (Map.Entry<String, StaticRoute> entry : staticRoutes.entrySet()) {
374 if (entry.getValue().compareTo(sRoute) == 0) {
375 return new Status(StatusCode.CONFLICT,
376 "This conflicts with an existing Static Route " +
377 "Configuration. Please check the configuration " +
381 staticRoutes.put(config.getName(), sRoute);
383 // Update config databse
384 staticRouteConfigs.put(config.getName(), config);
387 checkAndUpdateListeners(sRoute, true);
392 public Status removeStaticRoute(String name) {
393 staticRouteConfigs.remove(name);
394 StaticRoute sRoute = staticRoutes.remove(name);
395 if (sRoute != null) {
396 checkAndUpdateListeners(sRoute, false);
397 return new Status(StatusCode.SUCCESS, null);
399 return new Status(StatusCode.NOTFOUND,
400 "Static Route with name " + name + " is not found");
403 void setClusterContainerService(IClusterContainerServices s) {
404 log.debug("Cluster Service set");
405 this.clusterContainerService = s;
408 void unsetClusterContainerService(IClusterContainerServices s) {
409 if (this.clusterContainerService == s) {
410 log.debug("Cluster Service removed!");
411 this.clusterContainerService = null;
416 * Function called by the dependency manager when all the required
417 * dependencies are satisfied
420 void init(Component c) {
421 String containerName = null;
422 Dictionary props = c.getServiceProperties();
424 containerName = (String) props.get("containerName");
426 // In the Global instance case the containerName is empty
430 staticRoutesFileName = ROOT + "staticRouting_" + containerName
433 log.debug("forwarding.staticrouting starting on container {}",
435 //staticRoutes = new ConcurrentHashMap<String, StaticRoute>();
438 this.executor = Executors.newFixedThreadPool(1);
439 if (staticRouteConfigs.isEmpty()) {
444 * Slow probe to identify any gateway that might have silently appeared
445 * after the Static Routing Configuration.
447 gatewayProbeTimer = new Timer();
448 gatewayProbeTimer.schedule(new TimerTask() {
451 for (StaticRoute s : staticRoutes.values()) {
452 if ((s.getType() == StaticRoute.NextHopType.IPADDRESS)
453 && s.getHost() == null) {
454 checkAndUpdateListeners(s, true);
458 }, 60 * 1000, 60 * 1000);
462 * Function called by the dependency manager when at least one
463 * dependency become unsatisfied or when the component is shutting
464 * down because for example bundle is being stopped.
468 log.debug("Destroy all the Static Routing Rules given we are "
471 gatewayProbeTimer.cancel();
473 // Clear the listener so to be ready in next life
474 this.staticRoutingAware.clear();
478 * Function called by dependency manager after "init ()" is called
479 * and after the services provided by the class are registered in
480 * the service registry
487 * Function called by the dependency manager before the services
488 * exported by the component are unregistered, this will be
489 * followed by a "destroy ()" calls
497 public Status saveConfiguration() {
498 return this.saveConfig();