blob: 5dd4fc9d6154be35539ae606486cfafd576d2262 [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;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080038import com.netflix.curator.retry.ExponentialBackoffRetry;
Jonathan Hart1530ccc2013-04-03 19:36:02 -070039import com.netflix.curator.retry.RetryOneTime;
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070040import com.netflix.curator.x.discovery.ServiceCache;
41import com.netflix.curator.x.discovery.ServiceDiscovery;
42import com.netflix.curator.x.discovery.ServiceDiscoveryBuilder;
43import com.netflix.curator.x.discovery.ServiceInstance;
Jonathan Hartbd181b62013-02-17 16:05:38 -080044
Jonathan Hart7bf62172013-02-28 13:17:18 -080045/**
46 * A registry service that uses Zookeeper. All data is stored in Zookeeper,
47 * so this can be used as a global registry in a multi-node ONOS cluster.
48 * @author jono
49 *
50 */
Jonathan Hartbd766972013-02-22 15:13:03 -080051public class ZookeeperRegistry implements IFloodlightModule, IControllerRegistryService {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -080052
Yuta HIGUCHI6ac8d182013-10-22 15:24:56 -070053 protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
Jonathan Hartbd766972013-02-22 15:13:03 -080054 protected String controllerId = null;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080055
Jonathan Hart3d7730a2013-02-22 11:51:17 -080056 protected IRestApiService restApi;
57
Jonathan Hart7bf62172013-02-28 13:17:18 -080058 //This is the default, it's overwritten by the connectionString configuration parameter
Jonathan Hartbd181b62013-02-17 16:05:38 -080059 protected String connectionString = "localhost:2181";
Jonathan Hart3d7730a2013-02-22 11:51:17 -080060
Jonathan Hartbd181b62013-02-17 16:05:38 -080061 private final String namespace = "onos";
Jonathan Hartedd6a442013-02-20 15:22:06 -080062 private final String switchLatchesPath = "/switches";
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070063
64 private final String SERVICES_PATH = "/"; //i.e. the root of our namespace
65 private final String CONTROLLER_SERVICE_NAME = "controllers";
Jonathan Hartbd181b62013-02-17 16:05:38 -080066
67 protected CuratorFramework client;
Jonathan Hartedd6a442013-02-20 15:22:06 -080068
Jonathan Hart3d7730a2013-02-22 11:51:17 -080069 protected PathChildrenCache switchCache;
Jonathan Hartbd181b62013-02-17 16:05:38 -080070
Jonathan Hart89187372013-03-14 16:41:09 -070071 protected ConcurrentHashMap<String, SwitchLeadershipData> switches;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080072 protected Map<String, PathChildrenCache> switchPathCaches;
Jonathan Hartbd181b62013-02-17 16:05:38 -080073
Jonathan Hart1530ccc2013-04-03 19:36:02 -070074 private final String ID_COUNTER_PATH = "/flowidcounter";
75 private final Long ID_BLOCK_SIZE = 0x100000000L;
76 protected DistributedAtomicLong distributedIdCounter;
77
Jonathan Hart97801ac2013-02-26 14:29:16 -080078 //Zookeeper performance-related configuration
Jonathan Hart0b3eee42013-03-16 18:20:04 -070079 protected static final int sessionTimeout = 5000;
80 protected static final int connectionTimeout = 7000;
Jonathan Hart57080fb2013-02-21 10:55:46 -080081
Jonathan Hartbd181b62013-02-17 16:05:38 -080082
Jonathan Hart89187372013-03-14 16:41:09 -070083 protected class SwitchLeaderListener implements LeaderLatchListener{
Jonathan Hart0de09492013-03-13 14:37:21 -070084 String dpid;
85 LeaderLatch latch;
86
Jonathan Hart89187372013-03-14 16:41:09 -070087 public SwitchLeaderListener(String dpid, LeaderLatch latch){
Jonathan Hart0de09492013-03-13 14:37:21 -070088 this.dpid = dpid;
89 this.latch = latch;
90 }
91
92 @Override
93 public void leaderLatchEvent(CuratorFramework arg0,
94 LeaderLatchEvent arg1) {
Jonathan Hart89187372013-03-14 16:41:09 -070095 log.debug("Leadership changed for {}, now {}",
Jonathan Hart0de09492013-03-13 14:37:21 -070096 dpid, latch.hasLeadership());
97
Jonathan Hart89187372013-03-14 16:41:09 -070098 //Check that the leadership request is still active - the client
99 //may have since released the request or even begun another request
100 //(this is why we use == to check the object instance is the same)
101 SwitchLeadershipData swData = switches.get(dpid);
Naoki Shiota1a5ca912014-01-03 17:02:31 -0800102 if (swData != null) {
103 log.debug("Leadership data {} not found", dpid);
104 }
105
106 if (swData.getLatch() == latch){
Jonathan Hart89187372013-03-14 16:41:09 -0700107 swData.getCallback().controlChanged(
108 HexString.toLong(dpid), latch.hasLeadership());
109 }
110 else {
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700111 log.debug("Latch for {} has changed: old latch {} - new latch {}",
112 new Object[]{dpid, latch, swData.getLatch()});
Jonathan Hart89187372013-03-14 16:41:09 -0700113 }
Jonathan Hart0de09492013-03-13 14:37:21 -0700114 }
115 }
116
Naoki Shiotad00accf2013-06-25 14:40:37 -0700117 protected class SwitchPathCacheListener implements PathChildrenCacheListener {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800118 @Override
119 public void childEvent(CuratorFramework client,
120 PathChildrenCacheEvent event) throws Exception {
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700121 //log.debug("Root switch path cache got {} event", event.getType());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800122
123 String strSwitch = null;
124 if (event.getData() != null){
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800125 String[] splitted = event.getData().getPath().split("/");
126 strSwitch = splitted[splitted.length - 1];
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800127 }
128
129 switch (event.getType()){
130 case CHILD_ADDED:
131 case CHILD_UPDATED:
132 //Check we have a PathChildrenCache for this child, add one if not
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700133 synchronized (switchPathCaches){
134 if (switchPathCaches.get(strSwitch) == null){
135 PathChildrenCache pc = new PathChildrenCache(client,
136 event.getData().getPath(), true);
137 pc.start(StartMode.NORMAL);
138 switchPathCaches.put(strSwitch, pc);
139 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800140 }
141 break;
142 case CHILD_REMOVED:
143 //Remove our PathChildrenCache for this child
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700144 PathChildrenCache pc = null;
145 synchronized(switchPathCaches){
146 pc = switchPathCaches.remove(strSwitch);
147 }
148 if (pc != null){
149 pc.close();
150 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800151 break;
152 default:
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700153 //All other events are connection status events. We don't need to
154 //do anything as the path cache handles these on its own.
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800155 break;
156 }
157
158 }
159 };
Naoki Shiotad00accf2013-06-25 14:40:37 -0700160 /**
161 * Listens for changes to the switch znodes in Zookeeper. This maintains
162 * the second level of PathChildrenCaches that hold the controllers
163 * contending for each switch - there's one for each switch.
164 */
165 PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700166 protected ServiceDiscovery<ControllerService> serviceDiscovery;
167 protected ServiceCache<ControllerService> serviceCache;
Jonathan Hartedd6a442013-02-20 15:22:06 -0800168
Jonathan Hartbd181b62013-02-17 16:05:38 -0800169
170 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800171 public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800172 log.info("Requesting control for {}", HexString.toHexString(dpid));
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800173
Jonathan Hartbd766972013-02-22 15:13:03 -0800174 if (controllerId == null){
175 throw new RuntimeException("Must register a controller before calling requestControl");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800176 }
177
178 String dpidStr = HexString.toHexString(dpid);
179 String latchPath = switchLatchesPath + "/" + dpidStr;
180
Jonathan Hart89187372013-03-14 16:41:09 -0700181 if (switches.get(dpidStr) != null){
Jonathan Hart3c0eccd2013-03-12 22:32:50 -0700182 log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
Pankaj Berdeda7187b2013-03-18 15:24:59 -0700183 throw new RegistryException("Already contesting control for " + dpidStr);
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800184 }
185
Jonathan Hartbd766972013-02-22 15:13:03 -0800186 LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
Jonathan Hart89187372013-03-14 16:41:09 -0700187 latch.addListener(new SwitchLeaderListener(dpidStr, latch));
Jonathan Hartbd181b62013-02-17 16:05:38 -0800188
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700189
Jonathan Hart89187372013-03-14 16:41:09 -0700190 SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb);
191 SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
192
193 if (oldData != null){
194 //There was already data for that key in the map
195 //i.e. someone else got here first so we can't succeed
196 log.debug("Already requested control for {}", dpidStr);
197 throw new RegistryException("Already requested control for " + dpidStr);
198 }
199
200 //Now that we know we were able to add our latch to the collection,
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700201 //we can start the leader election in Zookeeper. However I don't know
202 //how to handle if the start fails - the latch is already in our
203 //switches list.
204 //TODO seems like there's a Curator bug when latch.start is called when
205 //there's no Zookeeper connection which causes two znodes to be put in
206 //Zookeeper at the latch path when we reconnect to Zookeeper.
Jonathan Hartbd181b62013-02-17 16:05:38 -0800207 try {
Jonathan Hartbd181b62013-02-17 16:05:38 -0800208 latch.start();
209 } catch (Exception e) {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800210 log.warn("Error starting leader latch: {}", e.getMessage());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800211 throw new RegistryException("Error starting leader latch for " + dpidStr, e);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800212 }
213
214 }
215
216 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800217 public void releaseControl(long dpid) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800218 log.info("Releasing control for {}", HexString.toHexString(dpid));
Jonathan Hart57080fb2013-02-21 10:55:46 -0800219
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800220 String dpidStr = HexString.toHexString(dpid);
221
Jonathan Hart89187372013-03-14 16:41:09 -0700222 SwitchLeadershipData swData = switches.remove(dpidStr);
223
224 if (swData == null) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800225 log.debug("Trying to release control of a switch we are not contesting");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800226 return;
227 }
Jonathan Hart89187372013-03-14 16:41:09 -0700228
Jonathan Hart89187372013-03-14 16:41:09 -0700229 LeaderLatch latch = swData.getLatch();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800230
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700231 latch.removeAllListeners();
232
Jonathan Hartbd181b62013-02-17 16:05:38 -0800233 try {
234 latch.close();
235 } catch (IOException e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800236 //I think it's OK not to do anything here. Either the node got
237 //deleted correctly, or the connection went down and the node got deleted.
Umesh Krishnaswamy0ef75ee2013-03-25 17:50:27 -0700238 log.debug("releaseControl: caught IOException {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800239 }
240 }
241
242 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800243 public boolean hasControl(long dpid) {
Jonathan Hart89187372013-03-14 16:41:09 -0700244 String dpidStr = HexString.toHexString(dpid);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800245
Jonathan Hart89187372013-03-14 16:41:09 -0700246 SwitchLeadershipData swData = switches.get(dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800247
Jonathan Hart89187372013-03-14 16:41:09 -0700248 if (swData == null) {
249 log.warn("No leader latch for dpid {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800250 return false;
251 }
252
Jonathan Hart89187372013-03-14 16:41:09 -0700253 return swData.getLatch().hasLeadership();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800254 }
255
256 @Override
Jonathan Hart7bf62172013-02-28 13:17:18 -0800257 public String getControllerId() {
Jonathan Hartbd766972013-02-22 15:13:03 -0800258 return controllerId;
Jonathan Hartbd181b62013-02-17 16:05:38 -0800259 }
260
Jonathan Hartedd6a442013-02-20 15:22:06 -0800261 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800262 public Collection<String> getAllControllers() throws RegistryException {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800263 log.debug("Getting all controllers");
Jonathan Hart1be46262013-02-20 16:43:51 -0800264
Jonathan Hartedd6a442013-02-20 15:22:06 -0800265 List<String> controllers = new ArrayList<String>();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700266 for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()){
267 String id = instance.getPayload().getControllerId();
268 if (!controllers.contains(id)){
269 controllers.add(id);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800270 }
Jonathan Hartedd6a442013-02-20 15:22:06 -0800271 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700272
Jonathan Hartedd6a442013-02-20 15:22:06 -0800273 return controllers;
274 }
275
276 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800277 public void registerController(String id) throws RegistryException {
Jonathan Hartd10008d2013-02-23 17:04:08 -0800278 if (controllerId != null) {
279 throw new RegistryException(
280 "Controller already registered with id " + controllerId);
281 }
Jonathan Hartbd766972013-02-22 15:13:03 -0800282
283 controllerId = id;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800284
Jonathan Hartedd6a442013-02-20 15:22:06 -0800285 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700286 ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
287 .name(CONTROLLER_SERVICE_NAME)
288 .payload(new ControllerService(controllerId))
289 //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
290 //.uriSpec(uriSpec)
291 .build();
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700292
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700293 serviceDiscovery.registerService(thisInstance);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800294 } catch (Exception e) {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700295 // TODO Auto-generated catch block
296 e.printStackTrace();
Jonathan Hartedd6a442013-02-20 15:22:06 -0800297 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700298
Jonathan Hartedd6a442013-02-20 15:22:06 -0800299 }
300
301 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800302 public String getControllerForSwitch(long dpid) throws RegistryException {
Jonathan Hart89187372013-03-14 16:41:09 -0700303 String dpidStr = HexString.toHexString(dpid);
Pankaj Berde017960a2013-03-14 20:32:26 -0700304
Jonathan Hart599c6b32013-03-24 22:42:02 -0700305 PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
306
307 if (switchCache == null){
Jonathan Hartedd6a442013-02-20 15:22:06 -0800308 log.warn("Tried to get controller for non-existent switch");
309 return null;
310 }
311
Jonathan Hartf4e80842013-03-26 23:55:02 -0700312 try {
313 //We've seen issues with these caches get stuck out of date, so we'll have to
314 //force them to refresh before each read. This slows down the method as it
315 //blocks on a Zookeeper query, however at the moment only the cleanup thread
316 //uses this and that isn't particularly time-sensitive.
317 switchCache.rebuild();
318 } catch (Exception e) {
319 // TODO Auto-generated catch block
320 e.printStackTrace();
321 }
322
Jonathan Hart599c6b32013-03-24 22:42:02 -0700323 List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700324
Jonathan Hart599c6b32013-03-24 22:42:02 -0700325 Collections.sort(
326 sortedData,
327 new Comparator<ChildData>(){
328 private String getSequenceNumber(String path){
329 return path.substring(path.lastIndexOf('-') + 1);
330 }
331 @Override
332 public int compare(ChildData lhs, ChildData rhs) {
333 return getSequenceNumber(lhs.getPath()).
334 compareTo(getSequenceNumber(rhs.getPath()));
335 }
336 }
337 );
Jonathan Hartedd6a442013-02-20 15:22:06 -0800338
Jonathan Hart56b296e2013-03-25 13:30:10 -0700339 if (sortedData.size() == 0){
340 return null;
341 }
342
Jonathan Hart599c6b32013-03-24 22:42:02 -0700343 return new String(sortedData.get(0).getData(), Charsets.UTF_8);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800344 }
345
346 @Override
347 public Collection<Long> getSwitchesControlledByController(String controllerId) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800348 //TODO remove this if not needed
Jonathan Hartbd766972013-02-22 15:13:03 -0800349 throw new RuntimeException("Not yet implemented");
Jonathan Hartedd6a442013-02-20 15:22:06 -0800350 }
Jonathan Hartbd181b62013-02-17 16:05:38 -0800351
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800352
Jonathan Hart89187372013-03-14 16:41:09 -0700353 //TODO what should happen when there's no ZK connection? Currently we just return
354 //the cache but this may lead to false impressions - i.e. we don't actually know
355 //what's in ZK so we shouldn't say we do
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800356 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800357 public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
358 Map<String, List<ControllerRegistryEntry>> data =
359 new HashMap<String, List<ControllerRegistryEntry>>();
360
361 for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()){
362 List<ControllerRegistryEntry> contendingControllers =
363 new ArrayList<ControllerRegistryEntry>();
364
365 if (entry.getValue().getCurrentData().size() < 1){
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700366 //TODO prevent even having the PathChildrenCache in this case
367 //log.info("Switch entry with no leader elections: {}", entry.getKey());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800368 continue;
369 }
370
371 for (ChildData d : entry.getValue().getCurrentData()) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800372
Jonathan Hartd10008d2013-02-23 17:04:08 -0800373 String controllerId = new String(d.getData(), Charsets.UTF_8);
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800374
375 String[] splitted = d.getPath().split("-");
376 int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
377
378 contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
379 }
380
381 Collections.sort(contendingControllers);
382 data.put(entry.getKey(), contendingControllers);
383 }
384 return data;
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800385 }
386
Naoki Shiotaa3b2dfa2013-06-27 13:52:24 -0700387 /**
388 * Returns a block of IDs which are unique and unused.
389 * Range of IDs is fixed size and is assigned incrementally as this method called.
390 * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
391 * requests come up simultaneously.
392 */
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700393 public IdBlock allocateUniqueIdBlock(){
394 try {
395 AtomicValue<Long> result = null;
396 do {
397 result = distributedIdCounter.add(ID_BLOCK_SIZE);
398 } while (result == null || !result.succeeded());
399
400 return new IdBlock(result.preValue(), result.postValue() - 1, ID_BLOCK_SIZE);
401 } catch (Exception e) {
402 log.error("Error allocating ID block");
403 }
404
405 return null;
406 }
407
Jonathan Hartbd181b62013-02-17 16:05:38 -0800408 /*
409 * IFloodlightModule
410 */
411
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800412 @Override
413 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800414 Collection<Class<? extends IFloodlightService>> l =
415 new ArrayList<Class<? extends IFloodlightService>>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800416 l.add(IControllerRegistryService.class);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800417 return l;
418 }
419
420 @Override
421 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
422 Map<Class<? extends IFloodlightService>, IFloodlightService> m =
423 new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800424 m.put(IControllerRegistryService.class, this);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800425 return m;
426 }
427
428 @Override
429 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800430 Collection<Class<? extends IFloodlightService>> l =
431 new ArrayList<Class<? extends IFloodlightService>>();
432 l.add(IRestApiService.class);
433 return l;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800434 }
435
Jonathan Hart89187372013-03-14 16:41:09 -0700436 //TODO currently blocks startup when it can't get a Zookeeper connection.
437 //Do we support starting up with no Zookeeper connection?
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800438 @Override
439 public void init (FloodlightModuleContext context) throws FloodlightModuleException {
Jonathan Hartbd766972013-02-22 15:13:03 -0800440 log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
441
Jonathan Hart97801ac2013-02-26 14:29:16 -0800442 //Read the Zookeeper connection string from the config
443 Map<String, String> configParams = context.getConfigParams(this);
444 String connectionString = configParams.get("connectionString");
445 if (connectionString != null){
446 this.connectionString = connectionString;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800447 }
Jonathan Hart97801ac2013-02-26 14:29:16 -0800448 log.info("Setting Zookeeper connection string to {}", this.connectionString);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800449
Jonathan Hart97801ac2013-02-26 14:29:16 -0800450 restApi = context.getServiceImpl(IRestApiService.class);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800451
Jonathan Hart89187372013-03-14 16:41:09 -0700452 switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700453 //switchPathCaches = new HashMap<String, PathChildrenCache>();
454 switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800455
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800456 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800457 client = CuratorFrameworkFactory.newClient(this.connectionString,
Jonathan Hartcc957a02013-02-26 10:39:04 -0800458 sessionTimeout, connectionTimeout, retryPolicy);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800459
460 client.start();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800461 client = client.usingNamespace(namespace);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800462
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700463 distributedIdCounter = new DistributedAtomicLong(
464 client,
465 ID_COUNTER_PATH,
466 new RetryOneTime(100));
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800467
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800468 switchCache = new PathChildrenCache(client, switchLatchesPath, true);
469 switchCache.getListenable().addListener(switchPathCacheListener);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800470
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700471 //Build the service discovery object
472 serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
473 .client(client).basePath(SERVICES_PATH).build();
474
475 //We read the list of services very frequently (GUI periodically queries them)
476 //so we'll cache them to cut down on Zookeeper queries.
477 serviceCache = serviceDiscovery.serviceCacheBuilder()
478 .name(CONTROLLER_SERVICE_NAME).build();
479
480
Jonathan Hartedd6a442013-02-20 15:22:06 -0800481 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700482 serviceDiscovery.start();
483 serviceCache.start();
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800484
485 //Don't prime the cache, we want a notification for each child node in the path
486 switchCache.start(StartMode.NORMAL);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800487 } catch (Exception e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800488 throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
489 + e.getMessage());
Jonathan Hartedd6a442013-02-20 15:22:06 -0800490 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800491 }
492
493 @Override
494 public void startUp (FloodlightModuleContext context) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800495 restApi.addRestletRoutable(new RegistryWebRoutable());
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800496 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800497}