Jonathan Hart | deda0ba | 2014-04-03 11:14:12 -0700 | [diff] [blame] | 1 | package net.onrc.onos.core.registry; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 2 | |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 3 | import java.io.IOException; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 4 | import java.util.ArrayList; |
| 5 | import java.util.Collection; |
Jonathan Hart | 3d7730a | 2013-02-22 11:51:17 -0800 | [diff] [blame] | 6 | import java.util.Collections; |
Jonathan Hart | 599c6b3 | 2013-03-24 22:42:02 -0700 | [diff] [blame] | 7 | import java.util.Comparator; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 8 | import java.util.HashMap; |
Jonathan Hart | edd6a44 | 2013-02-20 15:22:06 -0800 | [diff] [blame] | 9 | import java.util.List; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 10 | import java.util.Map; |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 11 | import java.util.Random; |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 12 | import java.util.concurrent.BlockingQueue; |
Jonathan Hart | 8918737 | 2013-03-14 16:41:09 -0700 | [diff] [blame] | 13 | import java.util.concurrent.ConcurrentHashMap; |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 14 | import java.util.concurrent.ExecutorService; |
| 15 | import java.util.concurrent.Executors; |
| 16 | import java.util.concurrent.LinkedBlockingQueue; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 17 | |
Pavlin Radoslavov | c35229e | 2014-02-06 16:19:37 -0800 | [diff] [blame] | 18 | import net.floodlightcontroller.core.IFloodlightProviderService; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 19 | import net.floodlightcontroller.core.module.FloodlightModuleContext; |
| 20 | import net.floodlightcontroller.core.module.FloodlightModuleException; |
| 21 | import net.floodlightcontroller.core.module.IFloodlightModule; |
| 22 | import net.floodlightcontroller.core.module.IFloodlightService; |
Jonathan Hart | 3d7730a | 2013-02-22 11:51:17 -0800 | [diff] [blame] | 23 | import net.floodlightcontroller.restserver.IRestApiService; |
Jonathan Hart | deda0ba | 2014-04-03 11:14:12 -0700 | [diff] [blame] | 24 | import net.onrc.onos.core.registry.web.RegistryWebRoutable; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 25 | |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 26 | import org.apache.curator.RetryPolicy; |
| 27 | import org.apache.curator.framework.CuratorFramework; |
| 28 | import org.apache.curator.framework.CuratorFrameworkFactory; |
| 29 | import org.apache.curator.framework.recipes.atomic.AtomicValue; |
| 30 | import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong; |
| 31 | import org.apache.curator.framework.recipes.cache.ChildData; |
| 32 | import org.apache.curator.framework.recipes.cache.PathChildrenCache; |
| 33 | import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode; |
| 34 | import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; |
| 35 | import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; |
| 36 | import org.apache.curator.framework.recipes.leader.LeaderLatch; |
| 37 | import org.apache.curator.framework.recipes.leader.LeaderLatchListener; |
| 38 | import org.apache.curator.framework.recipes.leader.Participant; |
| 39 | import org.apache.curator.retry.ExponentialBackoffRetry; |
| 40 | import org.apache.curator.retry.RetryOneTime; |
| 41 | import org.apache.curator.x.discovery.ServiceCache; |
| 42 | import org.apache.curator.x.discovery.ServiceDiscovery; |
| 43 | import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; |
| 44 | import org.apache.curator.x.discovery.ServiceInstance; |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 45 | import org.openflow.util.HexString; |
| 46 | import org.slf4j.Logger; |
| 47 | import org.slf4j.LoggerFactory; |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 48 | |
Jonathan Hart | d10008d | 2013-02-23 17:04:08 -0800 | [diff] [blame] | 49 | import com.google.common.base.Charsets; |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 50 | |
Jonathan Hart | 7bf6217 | 2013-02-28 13:17:18 -0800 | [diff] [blame] | 51 | /** |
| 52 | * A registry service that uses Zookeeper. All data is stored in Zookeeper, |
| 53 | * so this can be used as a global registry in a multi-node ONOS cluster. |
Jonathan Hart | 7bf6217 | 2013-02-28 13:17:18 -0800 | [diff] [blame] | 54 | * |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 55 | * @author jono |
Jonathan Hart | 7bf6217 | 2013-02-28 13:17:18 -0800 | [diff] [blame] | 56 | */ |
Jonathan Hart | bd76697 | 2013-02-22 15:13:03 -0800 | [diff] [blame] | 57 | public class ZookeeperRegistry implements IFloodlightModule, IControllerRegistryService { |
Jonathan Hart | c6eee9e | 2013-02-18 14:58:27 -0800 | [diff] [blame] | 58 | |
Ray Milkey | ec83894 | 2014-04-09 11:28:43 -0700 | [diff] [blame] | 59 | private static final Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class); |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 60 | protected String controllerId = null; |
Jonathan Hart | 71c0ffc | 2013-03-24 15:58:42 -0700 | [diff] [blame] | 61 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 62 | protected IRestApiService restApi; |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 63 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 64 | //This is the default, it's overwritten by the connectionString configuration parameter |
| 65 | protected String connectionString = "localhost:2181"; |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 66 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 67 | private final String namespace = "onos"; |
| 68 | private final String switchLatchesPath = "/switches"; |
Ray Milkey | 2476cac | 2014-04-08 11:03:21 -0700 | [diff] [blame] | 69 | private static final String CLUSTER_LEADER_PATH = "/cluster/leader"; |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 70 | |
Ray Milkey | 2476cac | 2014-04-08 11:03:21 -0700 | [diff] [blame] | 71 | private static final String SERVICES_PATH = "/"; //i.e. the root of our namespace |
| 72 | private static final String CONTROLLER_SERVICE_NAME = "controllers"; |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 73 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 74 | protected CuratorFramework client; |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 75 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 76 | protected PathChildrenCache switchCache; |
| 77 | |
| 78 | protected ConcurrentHashMap<String, SwitchLeadershipData> switches; |
| 79 | protected Map<String, PathChildrenCache> switchPathCaches; |
| 80 | |
| 81 | protected LeaderLatch clusterLeaderLatch; |
| 82 | protected ClusterLeaderListener clusterLeaderListener; |
| 83 | private static final long CLUSTER_LEADER_ELECTION_RETRY_MS = 100; |
| 84 | |
Ray Milkey | 2476cac | 2014-04-08 11:03:21 -0700 | [diff] [blame] | 85 | private static final String ID_COUNTER_PATH = "/flowidcounter"; |
| 86 | private static final Long ID_BLOCK_SIZE = 0x100000000L; |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 87 | protected DistributedAtomicLong distributedIdCounter; |
| 88 | |
| 89 | //Zookeeper performance-related configuration |
Ray Milkey | 5c9f2db | 2014-04-09 10:31:21 -0700 | [diff] [blame] | 90 | protected static final int SESSION_TIMEOUT = 5000; |
| 91 | protected static final int CONNECTION_TIMEOUT = 7000; |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 92 | |
| 93 | // |
| 94 | // Unique ID generation state |
| 95 | // TODO: The implementation must be updated to use the Zookeeper |
| 96 | // instead of a ramdon generator. |
| 97 | // |
| 98 | private static Random randomGenerator = new Random(); |
| 99 | private static int nextUniqueIdPrefix = 0; |
| 100 | private static int nextUniqueIdSuffix = 0; |
| 101 | |
| 102 | private final BlockingQueue<SwitchLeaderEvent> switchLeadershipEvents = |
| 103 | new LinkedBlockingQueue<SwitchLeaderEvent>(); |
| 104 | |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 105 | private ExecutorService eventThreadExecutorService; |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 106 | |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 107 | private static class SwitchLeaderEvent { |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 108 | public final long dpid; |
| 109 | public final boolean isLeader; |
| 110 | |
| 111 | public SwitchLeaderEvent(long dpid, boolean isLeader) { |
| 112 | this.dpid = dpid; |
| 113 | this.isLeader = isLeader; |
| 114 | } |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 115 | } |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 116 | |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 117 | /* |
| 118 | * Dispatcher thread for leadership change events coming from Curator. |
| 119 | */ |
| 120 | private void dispatchEvents() { |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 121 | while (!Thread.currentThread().isInterrupted()) { |
| 122 | try { |
| 123 | SwitchLeaderEvent event = switchLeadershipEvents.take(); |
| 124 | SwitchLeadershipData swData = switches.get(HexString.toHexString(event.dpid)); |
| 125 | if (swData == null) { |
| 126 | log.debug("Leadership data {} not found", event.dpid); |
| 127 | continue; |
| 128 | } |
| 129 | |
| 130 | swData.getCallback().controlChanged(event.dpid, event.isLeader); |
| 131 | } catch (InterruptedException e) { |
| 132 | Thread.currentThread().interrupt(); |
| 133 | break; |
| 134 | } catch (Exception e) { |
| 135 | log.error("Exception in registry event thread", e); |
| 136 | } |
| 137 | } |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 138 | } |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 139 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 140 | protected class SwitchLeaderListener implements LeaderLatchListener { |
| 141 | String dpid; |
| 142 | LeaderLatch latch; |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 143 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 144 | public SwitchLeaderListener(String dpid, LeaderLatch latch) { |
| 145 | this.dpid = dpid; |
| 146 | this.latch = latch; |
| 147 | } |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 148 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 149 | @Override |
| 150 | public void isLeader() { |
| 151 | log.debug("Became leader for {}", dpid); |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 152 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 153 | switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), true)); |
| 154 | } |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 155 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 156 | @Override |
| 157 | public void notLeader() { |
| 158 | log.debug("Lost leadership for {}", dpid); |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 159 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 160 | switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), false)); |
| 161 | } |
| 162 | } |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 163 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 164 | protected class SwitchPathCacheListener implements PathChildrenCacheListener { |
| 165 | @Override |
| 166 | public void childEvent(CuratorFramework client, |
| 167 | PathChildrenCacheEvent event) throws Exception { |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 168 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 169 | String strSwitch = null; |
| 170 | if (event.getData() != null) { |
| 171 | String[] splitted = event.getData().getPath().split("/"); |
| 172 | strSwitch = splitted[splitted.length - 1]; |
Nick Karanatsios | 8abe717 | 2014-02-19 20:31:48 -0800 | [diff] [blame] | 173 | } |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 174 | |
| 175 | switch (event.getType()) { |
| 176 | case CHILD_ADDED: |
| 177 | case CHILD_UPDATED: |
| 178 | //Check we have a PathChildrenCache for this child, add one if not |
| 179 | synchronized (switchPathCaches) { |
| 180 | if (switchPathCaches.get(strSwitch) == null) { |
| 181 | PathChildrenCache pc = new PathChildrenCache(client, |
| 182 | event.getData().getPath(), true); |
| 183 | pc.start(StartMode.NORMAL); |
| 184 | switchPathCaches.put(strSwitch, pc); |
| 185 | } |
| 186 | } |
| 187 | break; |
| 188 | case CHILD_REMOVED: |
| 189 | //Remove our PathChildrenCache for this child |
| 190 | PathChildrenCache pc = null; |
| 191 | synchronized (switchPathCaches) { |
| 192 | pc = switchPathCaches.remove(strSwitch); |
| 193 | } |
| 194 | if (pc != null) { |
| 195 | pc.close(); |
| 196 | } |
| 197 | break; |
| 198 | default: |
| 199 | //All other switchLeadershipEvents are connection status switchLeadershipEvents. We don't need to |
| 200 | //do anything as the path cache handles these on its own. |
| 201 | break; |
| 202 | } |
| 203 | |
| 204 | } |
| 205 | } |
| 206 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 207 | protected class ClusterLeaderListener implements LeaderLatchListener { |
| 208 | LeaderLatch latch; |
| 209 | |
| 210 | public ClusterLeaderListener(LeaderLatch latch) { |
| 211 | this.latch = latch; |
| 212 | } |
| 213 | |
| 214 | // |
| 215 | // NOTE: If we need to support callbacks when the |
| 216 | // leadership changes, those should be called here. |
| 217 | // |
| 218 | |
| 219 | @Override |
| 220 | public void isLeader() { |
| 221 | log.debug("Cluster leadership aquired"); |
| 222 | } |
| 223 | |
| 224 | @Override |
| 225 | public void notLeader() { |
| 226 | log.debug("Cluster leadership lost"); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Listens for changes to the switch znodes in Zookeeper. This maintains |
| 232 | * the second level of PathChildrenCaches that hold the controllers |
| 233 | * contending for each switch - there's one for each switch. |
| 234 | */ |
| 235 | PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener(); |
| 236 | protected ServiceDiscovery<ControllerService> serviceDiscovery; |
| 237 | protected ServiceCache<ControllerService> serviceCache; |
| 238 | |
| 239 | |
| 240 | @Override |
| 241 | public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException { |
| 242 | log.info("Requesting control for {}", HexString.toHexString(dpid)); |
| 243 | |
| 244 | if (controllerId == null) { |
| 245 | throw new RuntimeException("Must register a controller before calling requestControl"); |
| 246 | } |
| 247 | |
| 248 | String dpidStr = HexString.toHexString(dpid); |
| 249 | String latchPath = switchLatchesPath + "/" + dpidStr; |
| 250 | |
| 251 | if (switches.get(dpidStr) != null) { |
| 252 | log.debug("Already contesting {}, returning", HexString.toHexString(dpid)); |
| 253 | throw new RegistryException("Already contesting control for " + dpidStr); |
| 254 | } |
| 255 | |
| 256 | LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId); |
| 257 | SwitchLeaderListener listener = new SwitchLeaderListener(dpidStr, latch); |
| 258 | latch.addListener(listener); |
| 259 | |
| 260 | |
| 261 | SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb, listener); |
| 262 | SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData); |
| 263 | |
| 264 | if (oldData != null) { |
| 265 | //There was already data for that key in the map |
| 266 | //i.e. someone else got here first so we can't succeed |
| 267 | log.debug("Already requested control for {}", dpidStr); |
| 268 | throw new RegistryException("Already requested control for " + dpidStr); |
| 269 | } |
| 270 | |
| 271 | //Now that we know we were able to add our latch to the collection, |
| 272 | //we can start the leader election in Zookeeper. However I don't know |
| 273 | //how to handle if the start fails - the latch is already in our |
| 274 | //switches list. |
| 275 | //TODO seems like there's a Curator bug when latch.start is called when |
| 276 | //there's no Zookeeper connection which causes two znodes to be put in |
| 277 | //Zookeeper at the latch path when we reconnect to Zookeeper. |
| 278 | try { |
| 279 | latch.start(); |
| 280 | } catch (Exception e) { |
| 281 | log.warn("Error starting leader latch: {}", e.getMessage()); |
| 282 | throw new RegistryException("Error starting leader latch for " + dpidStr, e); |
| 283 | } |
| 284 | |
| 285 | } |
| 286 | |
| 287 | @Override |
| 288 | public void releaseControl(long dpid) { |
| 289 | log.info("Releasing control for {}", HexString.toHexString(dpid)); |
| 290 | |
| 291 | String dpidStr = HexString.toHexString(dpid); |
| 292 | |
| 293 | SwitchLeadershipData swData = switches.remove(dpidStr); |
| 294 | |
| 295 | if (swData == null) { |
| 296 | log.debug("Trying to release control of a switch we are not contesting"); |
| 297 | return; |
| 298 | } |
| 299 | |
| 300 | LeaderLatch latch = swData.getLatch(); |
| 301 | |
| 302 | latch.removeListener(swData.getListener()); |
| 303 | |
| 304 | try { |
| 305 | latch.close(); |
| 306 | } catch (IOException e) { |
| 307 | //I think it's OK not to do anything here. Either the node got |
| 308 | //deleted correctly, or the connection went down and the node got deleted. |
| 309 | log.debug("releaseControl: caught IOException {}", dpidStr); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | @Override |
| 314 | public boolean hasControl(long dpid) { |
| 315 | String dpidStr = HexString.toHexString(dpid); |
| 316 | |
| 317 | SwitchLeadershipData swData = switches.get(dpidStr); |
| 318 | |
| 319 | if (swData == null) { |
| 320 | log.warn("No leader latch for dpid {}", dpidStr); |
| 321 | return false; |
| 322 | } |
| 323 | |
| 324 | return swData.getLatch().hasLeadership(); |
| 325 | } |
| 326 | |
| 327 | @Override |
| 328 | public boolean isClusterLeader() { |
| 329 | return clusterLeaderLatch.hasLeadership(); |
| 330 | } |
| 331 | |
| 332 | @Override |
| 333 | public String getControllerId() { |
| 334 | return controllerId; |
| 335 | } |
| 336 | |
| 337 | @Override |
| 338 | public Collection<String> getAllControllers() throws RegistryException { |
| 339 | log.debug("Getting all controllers"); |
| 340 | |
| 341 | List<String> controllers = new ArrayList<String>(); |
| 342 | for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()) { |
| 343 | String id = instance.getPayload().getControllerId(); |
| 344 | if (!controllers.contains(id)) { |
| 345 | controllers.add(id); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | return controllers; |
| 350 | } |
| 351 | |
| 352 | @Override |
| 353 | public void registerController(String id) throws RegistryException { |
| 354 | if (controllerId != null) { |
| 355 | throw new RegistryException( |
| 356 | "Controller already registered with id " + controllerId); |
| 357 | } |
| 358 | |
| 359 | controllerId = id; |
| 360 | |
| 361 | try { |
| 362 | ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder() |
| 363 | .name(CONTROLLER_SERVICE_NAME) |
| 364 | .payload(new ControllerService(controllerId)) |
| 365 | //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port |
| 366 | //.uriSpec(uriSpec) |
| 367 | .build(); |
| 368 | |
| 369 | serviceDiscovery.registerService(thisInstance); |
| 370 | } catch (Exception e) { |
| 371 | // TODO Auto-generated catch block |
| 372 | e.printStackTrace(); |
| 373 | } |
| 374 | |
| 375 | } |
| 376 | |
| 377 | @Override |
| 378 | public String getControllerForSwitch(long dpid) throws RegistryException { |
| 379 | String dpidStr = HexString.toHexString(dpid); |
| 380 | |
| 381 | PathChildrenCache switchCache = switchPathCaches.get(dpidStr); |
| 382 | |
| 383 | if (switchCache == null) { |
| 384 | log.warn("Tried to get controller for non-existent switch"); |
Nick Karanatsios | 8abe717 | 2014-02-19 20:31:48 -0800 | [diff] [blame] | 385 | return null; |
| 386 | } |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 387 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 388 | try { |
| 389 | //We've seen issues with these caches get stuck out of date, so we'll have to |
| 390 | //force them to refresh before each read. This slows down the method as it |
| 391 | //blocks on a Zookeeper query, however at the moment only the cleanup thread |
| 392 | //uses this and that isn't particularly time-sensitive. |
| 393 | switchCache.rebuild(); |
| 394 | } catch (Exception e) { |
| 395 | // TODO Auto-generated catch block |
| 396 | e.printStackTrace(); |
| 397 | } |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 398 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 399 | List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData()); |
| 400 | |
| 401 | Collections.sort( |
| 402 | sortedData, |
| 403 | new Comparator<ChildData>() { |
| 404 | private String getSequenceNumber(String path) { |
| 405 | return path.substring(path.lastIndexOf('-') + 1); |
| 406 | } |
| 407 | |
| 408 | @Override |
| 409 | public int compare(ChildData lhs, ChildData rhs) { |
| 410 | return getSequenceNumber(lhs.getPath()). |
| 411 | compareTo(getSequenceNumber(rhs.getPath())); |
| 412 | } |
| 413 | } |
| 414 | ); |
| 415 | |
| 416 | if (sortedData.size() == 0) { |
| 417 | return null; |
| 418 | } |
| 419 | |
| 420 | return new String(sortedData.get(0).getData(), Charsets.UTF_8); |
| 421 | } |
| 422 | |
| 423 | @Override |
| 424 | public Collection<Long> getSwitchesControlledByController(String controllerId) { |
| 425 | //TODO remove this if not needed |
| 426 | throw new RuntimeException("Not yet implemented"); |
| 427 | } |
| 428 | |
| 429 | |
| 430 | //TODO what should happen when there's no ZK connection? Currently we just return |
| 431 | //the cache but this may lead to false impressions - i.e. we don't actually know |
| 432 | //what's in ZK so we shouldn't say we do |
| 433 | @Override |
| 434 | public Map<String, List<ControllerRegistryEntry>> getAllSwitches() { |
| 435 | Map<String, List<ControllerRegistryEntry>> data = |
| 436 | new HashMap<String, List<ControllerRegistryEntry>>(); |
| 437 | |
| 438 | for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()) { |
| 439 | List<ControllerRegistryEntry> contendingControllers = |
| 440 | new ArrayList<ControllerRegistryEntry>(); |
| 441 | |
| 442 | if (entry.getValue().getCurrentData().size() < 1) { |
| 443 | //TODO prevent even having the PathChildrenCache in this case |
| 444 | //log.info("Switch entry with no leader elections: {}", entry.getKey()); |
| 445 | continue; |
| 446 | } |
| 447 | |
| 448 | for (ChildData d : entry.getValue().getCurrentData()) { |
| 449 | |
| 450 | String controllerId = new String(d.getData(), Charsets.UTF_8); |
| 451 | |
| 452 | String[] splitted = d.getPath().split("-"); |
| 453 | int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]); |
| 454 | |
| 455 | contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber)); |
| 456 | } |
| 457 | |
| 458 | Collections.sort(contendingControllers); |
| 459 | data.put(entry.getKey(), contendingControllers); |
| 460 | } |
| 461 | return data; |
| 462 | } |
| 463 | |
| 464 | public IdBlock allocateUniqueIdBlock(long range) { |
| 465 | try { |
| 466 | AtomicValue<Long> result = null; |
| 467 | do { |
| 468 | result = distributedIdCounter.add(range); |
| 469 | } while (result == null || !result.succeeded()); |
| 470 | |
| 471 | return new IdBlock(result.preValue(), result.postValue() - 1, range); |
| 472 | } catch (Exception e) { |
| 473 | log.error("Error allocating ID block"); |
| 474 | } |
| 475 | return null; |
| 476 | } |
| 477 | |
| 478 | /** |
| 479 | * Returns a block of IDs which are unique and unused. |
| 480 | * Range of IDs is fixed size and is assigned incrementally as this method called. |
| 481 | * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when |
| 482 | * requests come up simultaneously. |
| 483 | */ |
| 484 | @Override |
| 485 | public IdBlock allocateUniqueIdBlock() { |
| 486 | return allocateUniqueIdBlock(ID_BLOCK_SIZE); |
| 487 | } |
| 488 | |
| 489 | /** |
| 490 | * Get a globally unique ID. |
| 491 | * |
| 492 | * @return a globally unique ID. |
| 493 | */ |
| 494 | @Override |
| 495 | public synchronized long getNextUniqueId() { |
| 496 | // |
| 497 | // Generate the next Unique ID. |
| 498 | // |
| 499 | // TODO: For now, the higher 32 bits are random, and |
| 500 | // the lower 32 bits are sequential. |
| 501 | // The implementation must be updated to use the Zookeeper |
| 502 | // to allocate the higher 32 bits (globally unique). |
| 503 | // |
| 504 | if ((nextUniqueIdSuffix & 0xffffffffL) == 0xffffffffL) { |
| 505 | nextUniqueIdPrefix = randomGenerator.nextInt(); |
| 506 | nextUniqueIdSuffix = 0; |
| 507 | } else { |
| 508 | nextUniqueIdSuffix++; |
| 509 | } |
| 510 | long result = (long) nextUniqueIdPrefix << 32; |
| 511 | result = result | (0xffffffffL & nextUniqueIdSuffix); |
| 512 | return result; |
| 513 | } |
| 514 | |
| 515 | /* |
| 516 | * IFloodlightModule |
| 517 | */ |
| 518 | |
| 519 | @Override |
| 520 | public Collection<Class<? extends IFloodlightService>> getModuleServices() { |
| 521 | Collection<Class<? extends IFloodlightService>> l = |
Jonathan Hart | 3d7730a | 2013-02-22 11:51:17 -0800 | [diff] [blame] | 522 | new ArrayList<Class<? extends IFloodlightService>>(); |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 523 | l.add(IControllerRegistryService.class); |
| 524 | return l; |
| 525 | } |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 526 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 527 | @Override |
| 528 | public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { |
| 529 | Map<Class<? extends IFloodlightService>, IFloodlightService> m = |
| 530 | new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); |
| 531 | m.put(IControllerRegistryService.class, this); |
| 532 | return m; |
| 533 | } |
Pavlin Radoslavov | 52163ed | 2014-03-19 11:39:34 -0700 | [diff] [blame] | 534 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 535 | @Override |
| 536 | public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { |
| 537 | Collection<Class<? extends IFloodlightService>> l = |
| 538 | new ArrayList<Class<? extends IFloodlightService>>(); |
| 539 | l.add(IFloodlightProviderService.class); |
| 540 | l.add(IRestApiService.class); |
| 541 | return l; |
| 542 | } |
Jonathan Hart | bd181b6 | 2013-02-17 16:05:38 -0800 | [diff] [blame] | 543 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 544 | //TODO currently blocks startup when it can't get a Zookeeper connection. |
| 545 | //Do we support starting up with no Zookeeper connection? |
| 546 | @Override |
| 547 | public void init(FloodlightModuleContext context) throws FloodlightModuleException { |
| 548 | log.info("Initialising the Zookeeper Registry - Zookeeper connection required"); |
Jonathan Hart | 97801ac | 2013-02-26 14:29:16 -0800 | [diff] [blame] | 549 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 550 | //Read the Zookeeper connection string from the config |
| 551 | Map<String, String> configParams = context.getConfigParams(this); |
| 552 | String connectionString = configParams.get("connectionString"); |
| 553 | if (connectionString != null) { |
| 554 | this.connectionString = connectionString; |
| 555 | } |
| 556 | log.info("Setting Zookeeper connection string to {}", this.connectionString); |
Jonathan Hart | 116b1fe | 2014-03-14 18:53:47 -0700 | [diff] [blame] | 557 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 558 | // |
| 559 | // Initialize the Unique ID generator |
| 560 | // TODO: This must be replaced by Zookeeper-based allocation |
| 561 | // |
| 562 | nextUniqueIdPrefix = randomGenerator.nextInt(); |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 563 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 564 | restApi = context.getServiceImpl(IRestApiService.class); |
Pavlin Radoslavov | f1377ce | 2014-02-05 17:37:24 -0800 | [diff] [blame] | 565 | |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 566 | switches = new ConcurrentHashMap<String, SwitchLeadershipData>(); |
| 567 | //switchPathCaches = new HashMap<String, PathChildrenCache>(); |
| 568 | switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>(); |
| 569 | |
| 570 | RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); |
| 571 | client = CuratorFrameworkFactory.newClient(this.connectionString, |
Ray Milkey | 5c9f2db | 2014-04-09 10:31:21 -0700 | [diff] [blame] | 572 | SESSION_TIMEOUT, CONNECTION_TIMEOUT, retryPolicy); |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 573 | |
| 574 | client.start(); |
| 575 | client = client.usingNamespace(namespace); |
| 576 | |
| 577 | distributedIdCounter = new DistributedAtomicLong( |
| 578 | client, |
| 579 | ID_COUNTER_PATH, |
| 580 | new RetryOneTime(100)); |
| 581 | |
| 582 | switchCache = new PathChildrenCache(client, switchLatchesPath, true); |
| 583 | switchCache.getListenable().addListener(switchPathCacheListener); |
| 584 | |
| 585 | //Build the service discovery object |
| 586 | serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class) |
| 587 | .client(client).basePath(SERVICES_PATH).build(); |
| 588 | |
| 589 | //We read the list of services very frequently (GUI periodically queries them) |
| 590 | //so we'll cache them to cut down on Zookeeper queries. |
| 591 | serviceCache = serviceDiscovery.serviceCacheBuilder() |
| 592 | .name(CONTROLLER_SERVICE_NAME).build(); |
| 593 | |
| 594 | |
| 595 | try { |
| 596 | serviceDiscovery.start(); |
| 597 | serviceCache.start(); |
| 598 | |
| 599 | //Don't prime the cache, we want a notification for each child node in the path |
| 600 | switchCache.start(StartMode.NORMAL); |
| 601 | } catch (Exception e) { |
| 602 | throw new FloodlightModuleException("Error initialising ZookeeperRegistry: " |
| 603 | + e.getMessage()); |
| 604 | } |
| 605 | |
| 606 | eventThreadExecutorService = Executors.newSingleThreadExecutor(); |
| 607 | eventThreadExecutorService.execute( |
| 608 | new Runnable() { |
| 609 | @Override |
| 610 | public void run() { |
| 611 | dispatchEvents(); |
| 612 | } |
| 613 | }); |
| 614 | } |
| 615 | |
| 616 | @Override |
| 617 | public void startUp(FloodlightModuleContext context) { |
| 618 | // |
| 619 | // Cluster Leader election setup. |
| 620 | // NOTE: We have to do it here, because during the init stage |
| 621 | // we don't know the Controller ID. |
| 622 | // |
| 623 | if (controllerId == null) { |
| 624 | log.error("Error on startup: unknown ControllerId"); |
| 625 | } |
| 626 | clusterLeaderLatch = new LeaderLatch(client, |
| 627 | CLUSTER_LEADER_PATH, |
| 628 | controllerId); |
| 629 | clusterLeaderListener = new ClusterLeaderListener(clusterLeaderLatch); |
| 630 | clusterLeaderLatch.addListener(clusterLeaderListener); |
| 631 | try { |
| 632 | clusterLeaderLatch.start(); |
| 633 | } catch (Exception e) { |
| 634 | log.error("Error on startup starting the cluster leader election: {}", e.getMessage()); |
| 635 | } |
| 636 | |
| 637 | // Keep trying until there is a cluster leader |
| 638 | do { |
| 639 | try { |
| 640 | Participant leader = clusterLeaderLatch.getLeader(); |
Ray Milkey | b29e626 | 2014-04-09 16:02:14 -0700 | [diff] [blame] | 641 | if (!leader.getId().isEmpty()) { |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 642 | break; |
Ray Milkey | b29e626 | 2014-04-09 16:02:14 -0700 | [diff] [blame] | 643 | } |
Ray Milkey | 269ffb9 | 2014-04-03 14:43:30 -0700 | [diff] [blame] | 644 | Thread.sleep(CLUSTER_LEADER_ELECTION_RETRY_MS); |
| 645 | } catch (Exception e) { |
| 646 | log.error("Error on startup waiting for cluster leader election: {}", e.getMessage()); |
| 647 | } |
| 648 | } while (true); |
| 649 | |
| 650 | restApi.addRestletRoutable(new RegistryWebRoutable()); |
| 651 | } |
Umesh Krishnaswamy | b56bb29 | 2013-02-12 20:28:27 -0800 | [diff] [blame] | 652 | } |