blob: b03aea2fac878547bec26b0cfb2b38c85f785279 [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);
102 if (swData != null && swData.getLatch() == latch){
103 swData.getCallback().controlChanged(
104 HexString.toLong(dpid), latch.hasLeadership());
105 }
106 else {
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700107 log.debug("Latch for {} has changed: old latch {} - new latch {}",
108 new Object[]{dpid, latch, swData.getLatch()});
Jonathan Hart89187372013-03-14 16:41:09 -0700109 }
Jonathan Hart0de09492013-03-13 14:37:21 -0700110 }
111 }
112
Naoki Shiotad00accf2013-06-25 14:40:37 -0700113 protected class SwitchPathCacheListener implements PathChildrenCacheListener {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800114 @Override
115 public void childEvent(CuratorFramework client,
116 PathChildrenCacheEvent event) throws Exception {
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700117 //log.debug("Root switch path cache got {} event", event.getType());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800118
119 String strSwitch = null;
120 if (event.getData() != null){
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800121 String[] splitted = event.getData().getPath().split("/");
122 strSwitch = splitted[splitted.length - 1];
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800123 }
124
125 switch (event.getType()){
126 case CHILD_ADDED:
127 case CHILD_UPDATED:
128 //Check we have a PathChildrenCache for this child, add one if not
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700129 synchronized (switchPathCaches){
130 if (switchPathCaches.get(strSwitch) == null){
131 PathChildrenCache pc = new PathChildrenCache(client,
132 event.getData().getPath(), true);
133 pc.start(StartMode.NORMAL);
134 switchPathCaches.put(strSwitch, pc);
135 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800136 }
137 break;
138 case CHILD_REMOVED:
139 //Remove our PathChildrenCache for this child
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700140 PathChildrenCache pc = null;
141 synchronized(switchPathCaches){
142 pc = switchPathCaches.remove(strSwitch);
143 }
144 if (pc != null){
145 pc.close();
146 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800147 break;
148 default:
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700149 //All other events are connection status events. We don't need to
150 //do anything as the path cache handles these on its own.
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800151 break;
152 }
153
154 }
155 };
Naoki Shiotad00accf2013-06-25 14:40:37 -0700156 /**
157 * Listens for changes to the switch znodes in Zookeeper. This maintains
158 * the second level of PathChildrenCaches that hold the controllers
159 * contending for each switch - there's one for each switch.
160 */
161 PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700162 protected ServiceDiscovery<ControllerService> serviceDiscovery;
163 protected ServiceCache<ControllerService> serviceCache;
Jonathan Hartedd6a442013-02-20 15:22:06 -0800164
Jonathan Hartbd181b62013-02-17 16:05:38 -0800165
166 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800167 public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800168 log.info("Requesting control for {}", HexString.toHexString(dpid));
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800169
Jonathan Hartbd766972013-02-22 15:13:03 -0800170 if (controllerId == null){
171 throw new RuntimeException("Must register a controller before calling requestControl");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800172 }
173
174 String dpidStr = HexString.toHexString(dpid);
175 String latchPath = switchLatchesPath + "/" + dpidStr;
176
Jonathan Hart89187372013-03-14 16:41:09 -0700177 if (switches.get(dpidStr) != null){
Jonathan Hart3c0eccd2013-03-12 22:32:50 -0700178 log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
Pankaj Berdeda7187b2013-03-18 15:24:59 -0700179 throw new RegistryException("Already contesting control for " + dpidStr);
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800180 }
181
Jonathan Hartbd766972013-02-22 15:13:03 -0800182 LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
Jonathan Hart89187372013-03-14 16:41:09 -0700183 latch.addListener(new SwitchLeaderListener(dpidStr, latch));
Jonathan Hartbd181b62013-02-17 16:05:38 -0800184
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700185
Jonathan Hart89187372013-03-14 16:41:09 -0700186 SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb);
187 SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
188
189 if (oldData != null){
190 //There was already data for that key in the map
191 //i.e. someone else got here first so we can't succeed
192 log.debug("Already requested control for {}", dpidStr);
193 throw new RegistryException("Already requested control for " + dpidStr);
194 }
195
196 //Now that we know we were able to add our latch to the collection,
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700197 //we can start the leader election in Zookeeper. However I don't know
198 //how to handle if the start fails - the latch is already in our
199 //switches list.
200 //TODO seems like there's a Curator bug when latch.start is called when
201 //there's no Zookeeper connection which causes two znodes to be put in
202 //Zookeeper at the latch path when we reconnect to Zookeeper.
Jonathan Hartbd181b62013-02-17 16:05:38 -0800203 try {
Jonathan Hartbd181b62013-02-17 16:05:38 -0800204 latch.start();
205 } catch (Exception e) {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800206 log.warn("Error starting leader latch: {}", e.getMessage());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800207 throw new RegistryException("Error starting leader latch for " + dpidStr, e);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800208 }
209
210 }
211
212 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800213 public void releaseControl(long dpid) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800214 log.info("Releasing control for {}", HexString.toHexString(dpid));
Jonathan Hart57080fb2013-02-21 10:55:46 -0800215
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800216 String dpidStr = HexString.toHexString(dpid);
217
Jonathan Hart89187372013-03-14 16:41:09 -0700218 SwitchLeadershipData swData = switches.remove(dpidStr);
219
220 if (swData == null) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800221 log.debug("Trying to release control of a switch we are not contesting");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800222 return;
223 }
Jonathan Hart89187372013-03-14 16:41:09 -0700224
Jonathan Hart89187372013-03-14 16:41:09 -0700225 LeaderLatch latch = swData.getLatch();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800226
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700227 latch.removeAllListeners();
228
Jonathan Hartbd181b62013-02-17 16:05:38 -0800229 try {
230 latch.close();
231 } catch (IOException e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800232 //I think it's OK not to do anything here. Either the node got
233 //deleted correctly, or the connection went down and the node got deleted.
Umesh Krishnaswamy0ef75ee2013-03-25 17:50:27 -0700234 log.debug("releaseControl: caught IOException {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800235 }
236 }
237
238 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800239 public boolean hasControl(long dpid) {
Jonathan Hart89187372013-03-14 16:41:09 -0700240 String dpidStr = HexString.toHexString(dpid);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800241
Jonathan Hart89187372013-03-14 16:41:09 -0700242 SwitchLeadershipData swData = switches.get(dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800243
Jonathan Hart89187372013-03-14 16:41:09 -0700244 if (swData == null) {
245 log.warn("No leader latch for dpid {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800246 return false;
247 }
248
Jonathan Hart89187372013-03-14 16:41:09 -0700249 return swData.getLatch().hasLeadership();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800250 }
251
252 @Override
Jonathan Hart7bf62172013-02-28 13:17:18 -0800253 public String getControllerId() {
Jonathan Hartbd766972013-02-22 15:13:03 -0800254 return controllerId;
Jonathan Hartbd181b62013-02-17 16:05:38 -0800255 }
256
Jonathan Hartedd6a442013-02-20 15:22:06 -0800257 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800258 public Collection<String> getAllControllers() throws RegistryException {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800259 log.debug("Getting all controllers");
Jonathan Hart1be46262013-02-20 16:43:51 -0800260
Jonathan Hartedd6a442013-02-20 15:22:06 -0800261 List<String> controllers = new ArrayList<String>();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700262 for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()){
263 String id = instance.getPayload().getControllerId();
264 if (!controllers.contains(id)){
265 controllers.add(id);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800266 }
Jonathan Hartedd6a442013-02-20 15:22:06 -0800267 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700268
Jonathan Hartedd6a442013-02-20 15:22:06 -0800269 return controllers;
270 }
271
272 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800273 public void registerController(String id) throws RegistryException {
Jonathan Hartd10008d2013-02-23 17:04:08 -0800274 if (controllerId != null) {
275 throw new RegistryException(
276 "Controller already registered with id " + controllerId);
277 }
Jonathan Hartbd766972013-02-22 15:13:03 -0800278
279 controllerId = id;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800280
Jonathan Hartedd6a442013-02-20 15:22:06 -0800281 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700282 ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
283 .name(CONTROLLER_SERVICE_NAME)
284 .payload(new ControllerService(controllerId))
285 //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
286 //.uriSpec(uriSpec)
287 .build();
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700288
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700289 serviceDiscovery.registerService(thisInstance);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800290 } catch (Exception e) {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700291 // TODO Auto-generated catch block
292 e.printStackTrace();
Jonathan Hartedd6a442013-02-20 15:22:06 -0800293 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700294
Jonathan Hartedd6a442013-02-20 15:22:06 -0800295 }
296
297 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800298 public String getControllerForSwitch(long dpid) throws RegistryException {
Jonathan Hart89187372013-03-14 16:41:09 -0700299 String dpidStr = HexString.toHexString(dpid);
Pankaj Berde017960a2013-03-14 20:32:26 -0700300
Jonathan Hart599c6b32013-03-24 22:42:02 -0700301 PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
302
303 if (switchCache == null){
Jonathan Hartedd6a442013-02-20 15:22:06 -0800304 log.warn("Tried to get controller for non-existent switch");
305 return null;
306 }
307
Jonathan Hartf4e80842013-03-26 23:55:02 -0700308 try {
309 //We've seen issues with these caches get stuck out of date, so we'll have to
310 //force them to refresh before each read. This slows down the method as it
311 //blocks on a Zookeeper query, however at the moment only the cleanup thread
312 //uses this and that isn't particularly time-sensitive.
313 switchCache.rebuild();
314 } catch (Exception e) {
315 // TODO Auto-generated catch block
316 e.printStackTrace();
317 }
318
Jonathan Hart599c6b32013-03-24 22:42:02 -0700319 List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700320
Jonathan Hart599c6b32013-03-24 22:42:02 -0700321 Collections.sort(
322 sortedData,
323 new Comparator<ChildData>(){
324 private String getSequenceNumber(String path){
325 return path.substring(path.lastIndexOf('-') + 1);
326 }
327 @Override
328 public int compare(ChildData lhs, ChildData rhs) {
329 return getSequenceNumber(lhs.getPath()).
330 compareTo(getSequenceNumber(rhs.getPath()));
331 }
332 }
333 );
Jonathan Hartedd6a442013-02-20 15:22:06 -0800334
Jonathan Hart56b296e2013-03-25 13:30:10 -0700335 if (sortedData.size() == 0){
336 return null;
337 }
338
Jonathan Hart599c6b32013-03-24 22:42:02 -0700339 return new String(sortedData.get(0).getData(), Charsets.UTF_8);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800340 }
341
342 @Override
343 public Collection<Long> getSwitchesControlledByController(String controllerId) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800344 //TODO remove this if not needed
Jonathan Hartbd766972013-02-22 15:13:03 -0800345 throw new RuntimeException("Not yet implemented");
Jonathan Hartedd6a442013-02-20 15:22:06 -0800346 }
Jonathan Hartbd181b62013-02-17 16:05:38 -0800347
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800348
Jonathan Hart89187372013-03-14 16:41:09 -0700349 //TODO what should happen when there's no ZK connection? Currently we just return
350 //the cache but this may lead to false impressions - i.e. we don't actually know
351 //what's in ZK so we shouldn't say we do
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800352 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800353 public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
354 Map<String, List<ControllerRegistryEntry>> data =
355 new HashMap<String, List<ControllerRegistryEntry>>();
356
357 for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()){
358 List<ControllerRegistryEntry> contendingControllers =
359 new ArrayList<ControllerRegistryEntry>();
360
361 if (entry.getValue().getCurrentData().size() < 1){
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700362 //TODO prevent even having the PathChildrenCache in this case
363 //log.info("Switch entry with no leader elections: {}", entry.getKey());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800364 continue;
365 }
366
367 for (ChildData d : entry.getValue().getCurrentData()) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800368
Jonathan Hartd10008d2013-02-23 17:04:08 -0800369 String controllerId = new String(d.getData(), Charsets.UTF_8);
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800370
371 String[] splitted = d.getPath().split("-");
372 int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
373
374 contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
375 }
376
377 Collections.sort(contendingControllers);
378 data.put(entry.getKey(), contendingControllers);
379 }
380 return data;
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800381 }
382
Naoki Shiotaa3b2dfa2013-06-27 13:52:24 -0700383 /**
384 * Returns a block of IDs which are unique and unused.
385 * Range of IDs is fixed size and is assigned incrementally as this method called.
386 * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
387 * requests come up simultaneously.
388 */
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700389 public IdBlock allocateUniqueIdBlock(){
390 try {
391 AtomicValue<Long> result = null;
392 do {
393 result = distributedIdCounter.add(ID_BLOCK_SIZE);
394 } while (result == null || !result.succeeded());
395
396 return new IdBlock(result.preValue(), result.postValue() - 1, ID_BLOCK_SIZE);
397 } catch (Exception e) {
398 log.error("Error allocating ID block");
399 }
400
401 return null;
402 }
403
Jonathan Hartbd181b62013-02-17 16:05:38 -0800404 /*
405 * IFloodlightModule
406 */
407
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800408 @Override
409 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800410 Collection<Class<? extends IFloodlightService>> l =
411 new ArrayList<Class<? extends IFloodlightService>>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800412 l.add(IControllerRegistryService.class);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800413 return l;
414 }
415
416 @Override
417 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
418 Map<Class<? extends IFloodlightService>, IFloodlightService> m =
419 new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800420 m.put(IControllerRegistryService.class, this);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800421 return m;
422 }
423
424 @Override
425 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800426 Collection<Class<? extends IFloodlightService>> l =
427 new ArrayList<Class<? extends IFloodlightService>>();
428 l.add(IRestApiService.class);
429 return l;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800430 }
431
Jonathan Hart89187372013-03-14 16:41:09 -0700432 //TODO currently blocks startup when it can't get a Zookeeper connection.
433 //Do we support starting up with no Zookeeper connection?
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800434 @Override
435 public void init (FloodlightModuleContext context) throws FloodlightModuleException {
Jonathan Hartbd766972013-02-22 15:13:03 -0800436 log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
437
Jonathan Hart97801ac2013-02-26 14:29:16 -0800438 //Read the Zookeeper connection string from the config
439 Map<String, String> configParams = context.getConfigParams(this);
440 String connectionString = configParams.get("connectionString");
441 if (connectionString != null){
442 this.connectionString = connectionString;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800443 }
Jonathan Hart97801ac2013-02-26 14:29:16 -0800444 log.info("Setting Zookeeper connection string to {}", this.connectionString);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800445
Jonathan Hart97801ac2013-02-26 14:29:16 -0800446 restApi = context.getServiceImpl(IRestApiService.class);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800447
Jonathan Hart89187372013-03-14 16:41:09 -0700448 switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700449 //switchPathCaches = new HashMap<String, PathChildrenCache>();
450 switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800451
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800452 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800453 client = CuratorFrameworkFactory.newClient(this.connectionString,
Jonathan Hartcc957a02013-02-26 10:39:04 -0800454 sessionTimeout, connectionTimeout, retryPolicy);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800455
456 client.start();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800457 client = client.usingNamespace(namespace);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800458
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700459 distributedIdCounter = new DistributedAtomicLong(
460 client,
461 ID_COUNTER_PATH,
462 new RetryOneTime(100));
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800463
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800464 switchCache = new PathChildrenCache(client, switchLatchesPath, true);
465 switchCache.getListenable().addListener(switchPathCacheListener);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800466
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700467 //Build the service discovery object
468 serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
469 .client(client).basePath(SERVICES_PATH).build();
470
471 //We read the list of services very frequently (GUI periodically queries them)
472 //so we'll cache them to cut down on Zookeeper queries.
473 serviceCache = serviceDiscovery.serviceCacheBuilder()
474 .name(CONTROLLER_SERVICE_NAME).build();
475
476
Jonathan Hartedd6a442013-02-20 15:22:06 -0800477 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700478 serviceDiscovery.start();
479 serviceCache.start();
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800480
481 //Don't prime the cache, we want a notification for each child node in the path
482 switchCache.start(StartMode.NORMAL);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800483 } catch (Exception e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800484 throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
485 + e.getMessage());
Jonathan Hartedd6a442013-02-20 15:22:06 -0800486 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800487 }
488
489 @Override
490 public void startUp (FloodlightModuleContext context) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800491 restApi.addRestletRoutable(new RegistryWebRoutable());
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800492 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800493}