blob: b4963215fa5a28af559c8cb2a49464630fc2c7d6 [file] [log] [blame]
Jonathan Hartd82f20d2013-02-21 18:04:24 -08001package net.onrc.onos.registry.controller;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -08002
Jonathan Hartbd181b62013-02-17 16:05:38 -08003import java.io.IOException;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -08004import java.util.ArrayList;
5import java.util.Collection;
Jonathan Hart3d7730a2013-02-22 11:51:17 -08006import java.util.Collections;
Jonathan Hart599c6b32013-03-24 22:42:02 -07007import java.util.Comparator;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -08008import java.util.HashMap;
Jonathan Hartedd6a442013-02-20 15:22:06 -08009import java.util.List;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080010import java.util.Map;
Jonathan Hart89187372013-03-14 16:41:09 -070011import java.util.concurrent.ConcurrentHashMap;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080012
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080013import net.floodlightcontroller.core.module.FloodlightModuleContext;
14import net.floodlightcontroller.core.module.FloodlightModuleException;
15import net.floodlightcontroller.core.module.IFloodlightModule;
16import net.floodlightcontroller.core.module.IFloodlightService;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080017import net.floodlightcontroller.restserver.IRestApiService;
Naoki Shiotab32edf52013-12-12 14:09:36 -080018import net.onrc.onos.registry.controller.web.RegistryWebRoutable;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080019
Jonathan Hartbd181b62013-02-17 16:05:38 -080020import org.openflow.util.HexString;
21import org.slf4j.Logger;
22import org.slf4j.LoggerFactory;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080023
Jonathan Hartd10008d2013-02-23 17:04:08 -080024import com.google.common.base.Charsets;
Jonathan Hartbd181b62013-02-17 16:05:38 -080025import com.netflix.curator.RetryPolicy;
26import com.netflix.curator.framework.CuratorFramework;
27import com.netflix.curator.framework.CuratorFrameworkFactory;
Jonathan Hart1530ccc2013-04-03 19:36:02 -070028import com.netflix.curator.framework.recipes.atomic.AtomicValue;
29import com.netflix.curator.framework.recipes.atomic.DistributedAtomicLong;
Jonathan Hartedd6a442013-02-20 15:22:06 -080030import com.netflix.curator.framework.recipes.cache.ChildData;
31import com.netflix.curator.framework.recipes.cache.PathChildrenCache;
32import com.netflix.curator.framework.recipes.cache.PathChildrenCache.StartMode;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080033import com.netflix.curator.framework.recipes.cache.PathChildrenCacheEvent;
34import com.netflix.curator.framework.recipes.cache.PathChildrenCacheListener;
Jonathan Hartbd181b62013-02-17 16:05:38 -080035import com.netflix.curator.framework.recipes.leader.LeaderLatch;
Jonathan Hart0de09492013-03-13 14:37:21 -070036import com.netflix.curator.framework.recipes.leader.LeaderLatchEvent;
37import com.netflix.curator.framework.recipes.leader.LeaderLatchListener;
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -080038import com.netflix.curator.framework.recipes.leader.Participant;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080039import com.netflix.curator.retry.ExponentialBackoffRetry;
Jonathan Hart1530ccc2013-04-03 19:36:02 -070040import com.netflix.curator.retry.RetryOneTime;
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070041import com.netflix.curator.x.discovery.ServiceCache;
42import com.netflix.curator.x.discovery.ServiceDiscovery;
43import com.netflix.curator.x.discovery.ServiceDiscoveryBuilder;
44import com.netflix.curator.x.discovery.ServiceInstance;
Nick Karanatsios8abe7172014-02-19 20:31:48 -080045import java.util.concurrent.ArrayBlockingQueue;
46import java.util.concurrent.BlockingQueue;
Jonathan Hartbd181b62013-02-17 16:05:38 -080047
Jonathan Hart7bf62172013-02-28 13:17:18 -080048/**
49 * A registry service that uses Zookeeper. All data is stored in Zookeeper,
50 * so this can be used as a global registry in a multi-node ONOS cluster.
51 * @author jono
52 *
53 */
Jonathan Hartbd766972013-02-22 15:13:03 -080054public class ZookeeperRegistry implements IFloodlightModule, IControllerRegistryService {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -080055
Yuta HIGUCHI6ac8d182013-10-22 15:24:56 -070056 protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
Jonathan Hartbd766972013-02-22 15:13:03 -080057 protected String controllerId = null;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080058
Jonathan Hart3d7730a2013-02-22 11:51:17 -080059 protected IRestApiService restApi;
60
Jonathan Hart7bf62172013-02-28 13:17:18 -080061 //This is the default, it's overwritten by the connectionString configuration parameter
Jonathan Hartbd181b62013-02-17 16:05:38 -080062 protected String connectionString = "localhost:2181";
Jonathan Hart3d7730a2013-02-22 11:51:17 -080063
Jonathan Hartbd181b62013-02-17 16:05:38 -080064 private final String namespace = "onos";
Jonathan Hartedd6a442013-02-20 15:22:06 -080065 private final String switchLatchesPath = "/switches";
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -080066 private final String CLUSTER_LEADER_PATH = "/cluster/leader";
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070067
68 private final String SERVICES_PATH = "/"; //i.e. the root of our namespace
69 private final String CONTROLLER_SERVICE_NAME = "controllers";
Jonathan Hartbd181b62013-02-17 16:05:38 -080070
71 protected CuratorFramework client;
Jonathan Hartedd6a442013-02-20 15:22:06 -080072
Jonathan Hart3d7730a2013-02-22 11:51:17 -080073 protected PathChildrenCache switchCache;
Jonathan Hartbd181b62013-02-17 16:05:38 -080074
Jonathan Hart89187372013-03-14 16:41:09 -070075 protected ConcurrentHashMap<String, SwitchLeadershipData> switches;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080076 protected Map<String, PathChildrenCache> switchPathCaches;
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -080077
78 protected LeaderLatch clusterLeaderLatch;
79 protected ClusterLeaderListener clusterLeaderListener;
80 private static final long CLUSTER_LEADER_ELECTION_RETRY_MS = 100;
81
Jonathan Hart1530ccc2013-04-03 19:36:02 -070082 private final String ID_COUNTER_PATH = "/flowidcounter";
83 private final Long ID_BLOCK_SIZE = 0x100000000L;
84 protected DistributedAtomicLong distributedIdCounter;
85
Jonathan Hart97801ac2013-02-26 14:29:16 -080086 //Zookeeper performance-related configuration
Jonathan Hart0b3eee42013-03-16 18:20:04 -070087 protected static final int sessionTimeout = 5000;
88 protected static final int connectionTimeout = 7000;
Nick Karanatsios8abe7172014-02-19 20:31:48 -080089 private volatile IdBlock idBlock = null;
Jonathan Hart57080fb2013-02-21 10:55:46 -080090
Jonathan Hartbd181b62013-02-17 16:05:38 -080091
Jonathan Hart89187372013-03-14 16:41:09 -070092 protected class SwitchLeaderListener implements LeaderLatchListener{
Jonathan Hart0de09492013-03-13 14:37:21 -070093 String dpid;
94 LeaderLatch latch;
95
Jonathan Hart89187372013-03-14 16:41:09 -070096 public SwitchLeaderListener(String dpid, LeaderLatch latch){
Jonathan Hart0de09492013-03-13 14:37:21 -070097 this.dpid = dpid;
98 this.latch = latch;
99 }
100
101 @Override
102 public void leaderLatchEvent(CuratorFramework arg0,
103 LeaderLatchEvent arg1) {
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800104 log.debug("Switch leadership changed for {}, now {}",
Jonathan Hart0de09492013-03-13 14:37:21 -0700105 dpid, latch.hasLeadership());
106
Jonathan Hart89187372013-03-14 16:41:09 -0700107 //Check that the leadership request is still active - the client
108 //may have since released the request or even begun another request
109 //(this is why we use == to check the object instance is the same)
110 SwitchLeadershipData swData = switches.get(dpid);
Naoki Shiota2999e3d2014-01-03 17:22:59 -0800111 if (swData == null) {
Naoki Shiota1a5ca912014-01-03 17:02:31 -0800112 log.debug("Leadership data {} not found", dpid);
Naoki Shiota2999e3d2014-01-03 17:22:59 -0800113 return;
Naoki Shiota1a5ca912014-01-03 17:02:31 -0800114 }
115
116 if (swData.getLatch() == latch){
Jonathan Hart89187372013-03-14 16:41:09 -0700117 swData.getCallback().controlChanged(
118 HexString.toLong(dpid), latch.hasLeadership());
119 }
120 else {
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700121 log.debug("Latch for {} has changed: old latch {} - new latch {}",
122 new Object[]{dpid, latch, swData.getLatch()});
Jonathan Hart89187372013-03-14 16:41:09 -0700123 }
Jonathan Hart0de09492013-03-13 14:37:21 -0700124 }
125 }
126
Naoki Shiotad00accf2013-06-25 14:40:37 -0700127 protected class SwitchPathCacheListener implements PathChildrenCacheListener {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800128 @Override
129 public void childEvent(CuratorFramework client,
130 PathChildrenCacheEvent event) throws Exception {
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700131 //log.debug("Root switch path cache got {} event", event.getType());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800132
133 String strSwitch = null;
134 if (event.getData() != null){
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800135 String[] splitted = event.getData().getPath().split("/");
136 strSwitch = splitted[splitted.length - 1];
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800137 }
138
139 switch (event.getType()){
140 case CHILD_ADDED:
141 case CHILD_UPDATED:
142 //Check we have a PathChildrenCache for this child, add one if not
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700143 synchronized (switchPathCaches){
144 if (switchPathCaches.get(strSwitch) == null){
145 PathChildrenCache pc = new PathChildrenCache(client,
146 event.getData().getPath(), true);
147 pc.start(StartMode.NORMAL);
148 switchPathCaches.put(strSwitch, pc);
149 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800150 }
151 break;
152 case CHILD_REMOVED:
153 //Remove our PathChildrenCache for this child
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700154 PathChildrenCache pc = null;
155 synchronized(switchPathCaches){
156 pc = switchPathCaches.remove(strSwitch);
157 }
158 if (pc != null){
159 pc.close();
160 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800161 break;
162 default:
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700163 //All other events are connection status events. We don't need to
164 //do anything as the path cache handles these on its own.
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800165 break;
166 }
167
168 }
169 };
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800170
171 protected class ClusterLeaderListener implements LeaderLatchListener {
172 LeaderLatch latch;
173
174 public ClusterLeaderListener(LeaderLatch latch) {
175 this.latch = latch;
176 }
177
178 @Override
179 public void leaderLatchEvent(CuratorFramework arg0,
180 LeaderLatchEvent arg1) {
181 log.debug("Cluster leadership changed, now {}",
182 latch.hasLeadership());
183 //
184 // NOTE: If we need to support callbacks when the
185 // leadership changes, those should be called here.
186 //
187 }
188 }
189
Naoki Shiotad00accf2013-06-25 14:40:37 -0700190 /**
191 * Listens for changes to the switch znodes in Zookeeper. This maintains
192 * the second level of PathChildrenCaches that hold the controllers
193 * contending for each switch - there's one for each switch.
194 */
195 PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700196 protected ServiceDiscovery<ControllerService> serviceDiscovery;
197 protected ServiceCache<ControllerService> serviceCache;
Jonathan Hartedd6a442013-02-20 15:22:06 -0800198
Jonathan Hartbd181b62013-02-17 16:05:38 -0800199
200 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800201 public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800202 log.info("Requesting control for {}", HexString.toHexString(dpid));
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800203
Jonathan Hartbd766972013-02-22 15:13:03 -0800204 if (controllerId == null){
205 throw new RuntimeException("Must register a controller before calling requestControl");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800206 }
207
208 String dpidStr = HexString.toHexString(dpid);
209 String latchPath = switchLatchesPath + "/" + dpidStr;
210
Jonathan Hart89187372013-03-14 16:41:09 -0700211 if (switches.get(dpidStr) != null){
Jonathan Hart3c0eccd2013-03-12 22:32:50 -0700212 log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
Pankaj Berdeda7187b2013-03-18 15:24:59 -0700213 throw new RegistryException("Already contesting control for " + dpidStr);
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800214 }
215
Jonathan Hartbd766972013-02-22 15:13:03 -0800216 LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
Jonathan Hart89187372013-03-14 16:41:09 -0700217 latch.addListener(new SwitchLeaderListener(dpidStr, latch));
Jonathan Hartbd181b62013-02-17 16:05:38 -0800218
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700219
Jonathan Hart89187372013-03-14 16:41:09 -0700220 SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb);
221 SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
222
223 if (oldData != null){
224 //There was already data for that key in the map
225 //i.e. someone else got here first so we can't succeed
226 log.debug("Already requested control for {}", dpidStr);
227 throw new RegistryException("Already requested control for " + dpidStr);
228 }
229
230 //Now that we know we were able to add our latch to the collection,
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700231 //we can start the leader election in Zookeeper. However I don't know
232 //how to handle if the start fails - the latch is already in our
233 //switches list.
234 //TODO seems like there's a Curator bug when latch.start is called when
235 //there's no Zookeeper connection which causes two znodes to be put in
236 //Zookeeper at the latch path when we reconnect to Zookeeper.
Jonathan Hartbd181b62013-02-17 16:05:38 -0800237 try {
Jonathan Hartbd181b62013-02-17 16:05:38 -0800238 latch.start();
239 } catch (Exception e) {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800240 log.warn("Error starting leader latch: {}", e.getMessage());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800241 throw new RegistryException("Error starting leader latch for " + dpidStr, e);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800242 }
243
244 }
245
246 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800247 public void releaseControl(long dpid) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800248 log.info("Releasing control for {}", HexString.toHexString(dpid));
Jonathan Hart57080fb2013-02-21 10:55:46 -0800249
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800250 String dpidStr = HexString.toHexString(dpid);
251
Jonathan Hart89187372013-03-14 16:41:09 -0700252 SwitchLeadershipData swData = switches.remove(dpidStr);
253
254 if (swData == null) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800255 log.debug("Trying to release control of a switch we are not contesting");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800256 return;
257 }
Jonathan Hart89187372013-03-14 16:41:09 -0700258
Jonathan Hart89187372013-03-14 16:41:09 -0700259 LeaderLatch latch = swData.getLatch();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800260
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700261 latch.removeAllListeners();
262
Jonathan Hartbd181b62013-02-17 16:05:38 -0800263 try {
264 latch.close();
265 } catch (IOException e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800266 //I think it's OK not to do anything here. Either the node got
267 //deleted correctly, or the connection went down and the node got deleted.
Umesh Krishnaswamy0ef75ee2013-03-25 17:50:27 -0700268 log.debug("releaseControl: caught IOException {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800269 }
270 }
271
272 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800273 public boolean hasControl(long dpid) {
Jonathan Hart89187372013-03-14 16:41:09 -0700274 String dpidStr = HexString.toHexString(dpid);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800275
Jonathan Hart89187372013-03-14 16:41:09 -0700276 SwitchLeadershipData swData = switches.get(dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800277
Jonathan Hart89187372013-03-14 16:41:09 -0700278 if (swData == null) {
279 log.warn("No leader latch for dpid {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800280 return false;
281 }
282
Jonathan Hart89187372013-03-14 16:41:09 -0700283 return swData.getLatch().hasLeadership();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800284 }
285
286 @Override
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800287 public boolean isClusterLeader() {
288 return clusterLeaderLatch.hasLeadership();
289 }
290
291 @Override
Jonathan Hart7bf62172013-02-28 13:17:18 -0800292 public String getControllerId() {
Jonathan Hartbd766972013-02-22 15:13:03 -0800293 return controllerId;
Jonathan Hartbd181b62013-02-17 16:05:38 -0800294 }
295
Jonathan Hartedd6a442013-02-20 15:22:06 -0800296 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800297 public Collection<String> getAllControllers() throws RegistryException {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800298 log.debug("Getting all controllers");
Jonathan Hart1be46262013-02-20 16:43:51 -0800299
Jonathan Hartedd6a442013-02-20 15:22:06 -0800300 List<String> controllers = new ArrayList<String>();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700301 for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()){
302 String id = instance.getPayload().getControllerId();
303 if (!controllers.contains(id)){
304 controllers.add(id);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800305 }
Jonathan Hartedd6a442013-02-20 15:22:06 -0800306 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700307
Jonathan Hartedd6a442013-02-20 15:22:06 -0800308 return controllers;
309 }
310
311 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800312 public void registerController(String id) throws RegistryException {
Jonathan Hartd10008d2013-02-23 17:04:08 -0800313 if (controllerId != null) {
314 throw new RegistryException(
315 "Controller already registered with id " + controllerId);
316 }
Jonathan Hartbd766972013-02-22 15:13:03 -0800317
318 controllerId = id;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800319
Jonathan Hartedd6a442013-02-20 15:22:06 -0800320 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700321 ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
322 .name(CONTROLLER_SERVICE_NAME)
323 .payload(new ControllerService(controllerId))
324 //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
325 //.uriSpec(uriSpec)
326 .build();
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700327
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700328 serviceDiscovery.registerService(thisInstance);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800329 } catch (Exception e) {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700330 // TODO Auto-generated catch block
331 e.printStackTrace();
Jonathan Hartedd6a442013-02-20 15:22:06 -0800332 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700333
Jonathan Hartedd6a442013-02-20 15:22:06 -0800334 }
335
336 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800337 public String getControllerForSwitch(long dpid) throws RegistryException {
Jonathan Hart89187372013-03-14 16:41:09 -0700338 String dpidStr = HexString.toHexString(dpid);
Pankaj Berde017960a2013-03-14 20:32:26 -0700339
Jonathan Hart599c6b32013-03-24 22:42:02 -0700340 PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
341
342 if (switchCache == null){
Jonathan Hartedd6a442013-02-20 15:22:06 -0800343 log.warn("Tried to get controller for non-existent switch");
344 return null;
345 }
346
Jonathan Hartf4e80842013-03-26 23:55:02 -0700347 try {
348 //We've seen issues with these caches get stuck out of date, so we'll have to
349 //force them to refresh before each read. This slows down the method as it
350 //blocks on a Zookeeper query, however at the moment only the cleanup thread
351 //uses this and that isn't particularly time-sensitive.
352 switchCache.rebuild();
353 } catch (Exception e) {
354 // TODO Auto-generated catch block
355 e.printStackTrace();
356 }
357
Jonathan Hart599c6b32013-03-24 22:42:02 -0700358 List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700359
Jonathan Hart599c6b32013-03-24 22:42:02 -0700360 Collections.sort(
361 sortedData,
362 new Comparator<ChildData>(){
363 private String getSequenceNumber(String path){
364 return path.substring(path.lastIndexOf('-') + 1);
365 }
366 @Override
367 public int compare(ChildData lhs, ChildData rhs) {
368 return getSequenceNumber(lhs.getPath()).
369 compareTo(getSequenceNumber(rhs.getPath()));
370 }
371 }
372 );
Jonathan Hartedd6a442013-02-20 15:22:06 -0800373
Jonathan Hart56b296e2013-03-25 13:30:10 -0700374 if (sortedData.size() == 0){
375 return null;
376 }
377
Jonathan Hart599c6b32013-03-24 22:42:02 -0700378 return new String(sortedData.get(0).getData(), Charsets.UTF_8);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800379 }
380
381 @Override
382 public Collection<Long> getSwitchesControlledByController(String controllerId) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800383 //TODO remove this if not needed
Jonathan Hartbd766972013-02-22 15:13:03 -0800384 throw new RuntimeException("Not yet implemented");
Jonathan Hartedd6a442013-02-20 15:22:06 -0800385 }
Jonathan Hartbd181b62013-02-17 16:05:38 -0800386
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800387
Jonathan Hart89187372013-03-14 16:41:09 -0700388 //TODO what should happen when there's no ZK connection? Currently we just return
389 //the cache but this may lead to false impressions - i.e. we don't actually know
390 //what's in ZK so we shouldn't say we do
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800391 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800392 public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
393 Map<String, List<ControllerRegistryEntry>> data =
394 new HashMap<String, List<ControllerRegistryEntry>>();
395
396 for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()){
397 List<ControllerRegistryEntry> contendingControllers =
398 new ArrayList<ControllerRegistryEntry>();
399
400 if (entry.getValue().getCurrentData().size() < 1){
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700401 //TODO prevent even having the PathChildrenCache in this case
402 //log.info("Switch entry with no leader elections: {}", entry.getKey());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800403 continue;
404 }
405
406 for (ChildData d : entry.getValue().getCurrentData()) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800407
Jonathan Hartd10008d2013-02-23 17:04:08 -0800408 String controllerId = new String(d.getData(), Charsets.UTF_8);
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800409
410 String[] splitted = d.getPath().split("-");
411 int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
412
413 contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
414 }
415
416 Collections.sort(contendingControllers);
417 data.put(entry.getKey(), contendingControllers);
418 }
419 return data;
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800420 }
421
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800422 public IdBlock allocateUniqueIdBlock(long range) {
423 try {
424 AtomicValue<Long> result = null;
425 do {
426 result = distributedIdCounter.add(range);
427 } while (result == null || !result.succeeded());
428
429 return new IdBlock(result.preValue(), result.postValue() - 1, range);
430 } catch (Exception e) {
431 log.error("Error allocating ID block");
432 }
433 return null;
434 }
435
Naoki Shiotaa3b2dfa2013-06-27 13:52:24 -0700436 /**
437 * Returns a block of IDs which are unique and unused.
438 * Range of IDs is fixed size and is assigned incrementally as this method called.
439 * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
440 * requests come up simultaneously.
441 */
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800442 @Override
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700443 public IdBlock allocateUniqueIdBlock(){
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800444 return allocateUniqueIdBlock(ID_BLOCK_SIZE);
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700445 }
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800446
Jonathan Hartbd181b62013-02-17 16:05:38 -0800447 /*
448 * IFloodlightModule
449 */
450
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800451 @Override
452 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800453 Collection<Class<? extends IFloodlightService>> l =
454 new ArrayList<Class<? extends IFloodlightService>>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800455 l.add(IControllerRegistryService.class);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800456 return l;
457 }
458
459 @Override
460 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
461 Map<Class<? extends IFloodlightService>, IFloodlightService> m =
462 new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800463 m.put(IControllerRegistryService.class, this);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800464 return m;
465 }
466
467 @Override
468 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800469 Collection<Class<? extends IFloodlightService>> l =
470 new ArrayList<Class<? extends IFloodlightService>>();
471 l.add(IRestApiService.class);
472 return l;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800473 }
474
Jonathan Hart89187372013-03-14 16:41:09 -0700475 //TODO currently blocks startup when it can't get a Zookeeper connection.
476 //Do we support starting up with no Zookeeper connection?
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800477 @Override
478 public void init (FloodlightModuleContext context) throws FloodlightModuleException {
Jonathan Hartbd766972013-02-22 15:13:03 -0800479 log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
480
Jonathan Hart97801ac2013-02-26 14:29:16 -0800481 //Read the Zookeeper connection string from the config
482 Map<String, String> configParams = context.getConfigParams(this);
483 String connectionString = configParams.get("connectionString");
484 if (connectionString != null){
485 this.connectionString = connectionString;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800486 }
Jonathan Hart97801ac2013-02-26 14:29:16 -0800487 log.info("Setting Zookeeper connection string to {}", this.connectionString);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800488
Jonathan Hart97801ac2013-02-26 14:29:16 -0800489 restApi = context.getServiceImpl(IRestApiService.class);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800490
Jonathan Hart89187372013-03-14 16:41:09 -0700491 switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700492 //switchPathCaches = new HashMap<String, PathChildrenCache>();
493 switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800494
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800495 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800496 client = CuratorFrameworkFactory.newClient(this.connectionString,
Jonathan Hartcc957a02013-02-26 10:39:04 -0800497 sessionTimeout, connectionTimeout, retryPolicy);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800498
499 client.start();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800500 client = client.usingNamespace(namespace);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800501
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700502 distributedIdCounter = new DistributedAtomicLong(
503 client,
504 ID_COUNTER_PATH,
505 new RetryOneTime(100));
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800506
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800507 switchCache = new PathChildrenCache(client, switchLatchesPath, true);
508 switchCache.getListenable().addListener(switchPathCacheListener);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800509
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700510 //Build the service discovery object
511 serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
512 .client(client).basePath(SERVICES_PATH).build();
513
514 //We read the list of services very frequently (GUI periodically queries them)
515 //so we'll cache them to cut down on Zookeeper queries.
516 serviceCache = serviceDiscovery.serviceCacheBuilder()
517 .name(CONTROLLER_SERVICE_NAME).build();
518
519
Jonathan Hartedd6a442013-02-20 15:22:06 -0800520 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700521 serviceDiscovery.start();
522 serviceCache.start();
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800523
524 //Don't prime the cache, we want a notification for each child node in the path
525 switchCache.start(StartMode.NORMAL);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800526 } catch (Exception e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800527 throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
528 + e.getMessage());
Jonathan Hartedd6a442013-02-20 15:22:06 -0800529 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800530 }
531
532 @Override
533 public void startUp (FloodlightModuleContext context) {
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800534 //
535 // Cluster Leader election setup.
536 // NOTE: We have to do it here, because during the init stage
537 // we don't know the Controller ID.
538 //
539 if (controllerId == null) {
540 log.error("Error on startup: unknown ControllerId");
541 }
542 clusterLeaderLatch = new LeaderLatch(client,
543 CLUSTER_LEADER_PATH,
544 controllerId);
545 clusterLeaderListener = new ClusterLeaderListener(clusterLeaderLatch);
546 clusterLeaderLatch.addListener(clusterLeaderListener);
547 try {
548 clusterLeaderLatch.start();
549 } catch (Exception e) {
550 log.error("Error on startup starting the cluster leader election: {}", e.getMessage());
551 }
552
553 // Keep trying until there is a cluster leader
554 do {
555 try {
556 Participant leader = clusterLeaderLatch.getLeader();
557 if (! leader.getId().isEmpty())
558 break;
559 Thread.sleep(CLUSTER_LEADER_ELECTION_RETRY_MS);
560 } catch (Exception e) {
561 log.error("Error on startup waiting for cluster leader election: {}", e.getMessage());
562 }
563 } while (true);
564
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800565 restApi.addRestletRoutable(new RegistryWebRoutable());
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800566 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800567}