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 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;
77 void setStaticRoutingAware(IStaticRoutingAware s) {
78 if (this.staticRoutingAware != null) {
79 this.staticRoutingAware.add(s);
83 void unsetStaticRoutingAware(IStaticRoutingAware s) {
84 if (this.staticRoutingAware != null) {
85 this.staticRoutingAware.remove(s);
89 public void setHostTracker(IfIptoHost hostTracker) {
90 log.debug("Setting HostTracker");
91 this.hostTracker = hostTracker;
94 public void unsetHostTracker(IfIptoHost hostTracker) {
95 if (this.hostTracker == hostTracker) {
96 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 (Exception e) {
240 log.debug("Next hop {} is found", nh.getHostAddress());
241 staticRoute.setHost(host);
242 notifyStaticRouteUpdate(staticRoute, added);
244 log.debug("Next hop {} is still not present, try again later", nh.getHostAddress());
251 private void checkAndUpdateListeners(StaticRoute staticRoute, boolean added) {
252 NotifyStaticRouteWorker worker = new NotifyStaticRouteWorker(staticRoute, added);
254 executor.submit(worker);
255 } catch (Exception e) {
256 log.error("got Exception ", e);
260 private void notifyHostUpdate(HostNodeConnector host, boolean added) {
263 for (StaticRoute s : staticRoutes.values()) {
264 if (s.getType() == StaticRoute.NextHopType.SWITCHPORT)
266 if (s.getNextHopAddress().equals(host.getNetworkAddress())) {
272 notifyStaticRouteUpdate(s, added);
278 public void notifyHTClient(HostNodeConnector host) {
279 notifyHostUpdate(host, true);
283 public void notifyHTClientHostRemoved(HostNodeConnector host) {
284 notifyHostUpdate(host, false);
287 public boolean isIPv4AddressValid(String cidr) {
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]);
296 log.debug("IPv4 source address {} is not valid", cidr);
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);
309 public static short getUnsignedByte(ByteBuffer bb, int position) {
310 return ((short) (bb.get(position) & (short) 0xff));
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)) {
317 } else if (getUnsignedByte(buf1, i) < getUnsignedByte(buf2, i)) {
325 public StaticRoute getBestMatchStaticRoute(InetAddress ipAddress) {
326 ByteBuffer bblongestPrefix = null;
328 bblongestPrefix = ByteBuffer.wrap(InetAddress.getByName("0.0.0.0")
330 } catch (Exception e) {
334 if (staticRoutes == null) {
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;
349 return longestPrefixRoute;
352 public Status addStaticRoute(StaticRouteConfig config) {
355 status = config.isValid();
356 if (!status.isSuccess()) {
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");
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 " +
373 staticRouteConfigs.put(config.getName(), config);
374 StaticRoute sRoute = new StaticRoute(config);
375 staticRoutes.put(config.getName(), sRoute);
376 checkAndUpdateListeners(sRoute, true);
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);
387 return new Status(StatusCode.NOTFOUND,
388 "Static Route with name " + name + " is not found");
391 void setClusterContainerService(IClusterContainerServices s) {
392 log.debug("Cluster Service set");
393 this.clusterContainerService = s;
396 void unsetClusterContainerService(IClusterContainerServices s) {
397 if (this.clusterContainerService == s) {
398 log.debug("Cluster Service removed!");
399 this.clusterContainerService = null;
404 * Function called by the dependency manager when all the required
405 * dependencies are satisfied
408 void init(Component c) {
409 String containerName = null;
410 Dictionary props = c.getServiceProperties();
412 containerName = (String) props.get("containerName");
414 // In the Global instance case the containerName is empty
418 staticRoutesFileName = ROOT + "staticRouting_" + containerName
421 log.debug("forwarding.staticrouting starting on container {}",
423 //staticRoutes = new ConcurrentHashMap<String, StaticRoute>();
426 this.executor = Executors.newFixedThreadPool(1);
427 if (staticRouteConfigs.isEmpty())
431 * Slow probe to identify any gateway that might have silently appeared
432 * after the Static Routing Configuration.
434 gatewayProbeTimer = new Timer();
435 gatewayProbeTimer.schedule(new TimerTask() {
438 for (StaticRoute s : staticRoutes.values()) {
439 if ((s.getType() == StaticRoute.NextHopType.IPADDRESS)
440 && s.getHost() == null) {
441 checkAndUpdateListeners(s, true);
445 }, 60 * 1000, 60 * 1000);
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.
455 log.debug("Destroy all the Static Routing Rules given we are "
458 gatewayProbeTimer.cancel();
460 // Clear the listener so to be ready in next life
461 this.staticRoutingAware.clear();
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
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
484 public Status saveConfiguration() {
485 return this.saveConfig();