blob: 50ee1373c12b480010587194a4451633e13421ae [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;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080018
Jonathan Hartbd181b62013-02-17 16:05:38 -080019import org.openflow.util.HexString;
20import org.slf4j.Logger;
21import org.slf4j.LoggerFactory;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080022
Jonathan Hartd10008d2013-02-23 17:04:08 -080023import com.google.common.base.Charsets;
Jonathan Hartbd181b62013-02-17 16:05:38 -080024import com.netflix.curator.RetryPolicy;
25import com.netflix.curator.framework.CuratorFramework;
26import com.netflix.curator.framework.CuratorFrameworkFactory;
Jonathan Hart1530ccc2013-04-03 19:36:02 -070027import com.netflix.curator.framework.recipes.atomic.AtomicValue;
28import com.netflix.curator.framework.recipes.atomic.DistributedAtomicLong;
Jonathan Hartedd6a442013-02-20 15:22:06 -080029import com.netflix.curator.framework.recipes.cache.ChildData;
30import com.netflix.curator.framework.recipes.cache.PathChildrenCache;
31import com.netflix.curator.framework.recipes.cache.PathChildrenCache.StartMode;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080032import com.netflix.curator.framework.recipes.cache.PathChildrenCacheEvent;
33import com.netflix.curator.framework.recipes.cache.PathChildrenCacheListener;
Jonathan Hartbd181b62013-02-17 16:05:38 -080034import com.netflix.curator.framework.recipes.leader.LeaderLatch;
Jonathan Hart0de09492013-03-13 14:37:21 -070035import com.netflix.curator.framework.recipes.leader.LeaderLatchEvent;
36import com.netflix.curator.framework.recipes.leader.LeaderLatchListener;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080037import com.netflix.curator.retry.ExponentialBackoffRetry;
Jonathan Hart1530ccc2013-04-03 19:36:02 -070038import com.netflix.curator.retry.RetryOneTime;
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070039import com.netflix.curator.x.discovery.ServiceCache;
40import com.netflix.curator.x.discovery.ServiceDiscovery;
41import com.netflix.curator.x.discovery.ServiceDiscoveryBuilder;
42import com.netflix.curator.x.discovery.ServiceInstance;
Jonathan Hartbd181b62013-02-17 16:05:38 -080043
Jonathan Hart7bf62172013-02-28 13:17:18 -080044/**
45 * A registry service that uses Zookeeper. All data is stored in Zookeeper,
46 * so this can be used as a global registry in a multi-node ONOS cluster.
47 * @author jono
48 *
49 */
Jonathan Hartbd766972013-02-22 15:13:03 -080050public class ZookeeperRegistry implements IFloodlightModule, IControllerRegistryService {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -080051
Yuta HIGUCHI6ac8d182013-10-22 15:24:56 -070052 protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
Jonathan Hartbd766972013-02-22 15:13:03 -080053 protected String controllerId = null;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -080054
Jonathan Hart3d7730a2013-02-22 11:51:17 -080055 protected IRestApiService restApi;
56
Jonathan Hart7bf62172013-02-28 13:17:18 -080057 //This is the default, it's overwritten by the connectionString configuration parameter
Jonathan Hartbd181b62013-02-17 16:05:38 -080058 protected String connectionString = "localhost:2181";
Jonathan Hart3d7730a2013-02-22 11:51:17 -080059
Jonathan Hartbd181b62013-02-17 16:05:38 -080060 private final String namespace = "onos";
Jonathan Hartedd6a442013-02-20 15:22:06 -080061 private final String switchLatchesPath = "/switches";
Jonathan Hart71c0ffc2013-03-24 15:58:42 -070062
63 private final String SERVICES_PATH = "/"; //i.e. the root of our namespace
64 private final String CONTROLLER_SERVICE_NAME = "controllers";
Jonathan Hartbd181b62013-02-17 16:05:38 -080065
66 protected CuratorFramework client;
Jonathan Hartedd6a442013-02-20 15:22:06 -080067
Jonathan Hart3d7730a2013-02-22 11:51:17 -080068 protected PathChildrenCache switchCache;
Jonathan Hartbd181b62013-02-17 16:05:38 -080069
Jonathan Hart89187372013-03-14 16:41:09 -070070 protected ConcurrentHashMap<String, SwitchLeadershipData> switches;
Jonathan Hart3d7730a2013-02-22 11:51:17 -080071 protected Map<String, PathChildrenCache> switchPathCaches;
Jonathan Hartbd181b62013-02-17 16:05:38 -080072
Jonathan Hart1530ccc2013-04-03 19:36:02 -070073 private final String ID_COUNTER_PATH = "/flowidcounter";
74 private final Long ID_BLOCK_SIZE = 0x100000000L;
75 protected DistributedAtomicLong distributedIdCounter;
76
Jonathan Hart97801ac2013-02-26 14:29:16 -080077 //Zookeeper performance-related configuration
Jonathan Hart0b3eee42013-03-16 18:20:04 -070078 protected static final int sessionTimeout = 5000;
79 protected static final int connectionTimeout = 7000;
Jonathan Hart57080fb2013-02-21 10:55:46 -080080
Jonathan Hartbd181b62013-02-17 16:05:38 -080081
Jonathan Hart89187372013-03-14 16:41:09 -070082 protected class SwitchLeaderListener implements LeaderLatchListener{
Jonathan Hart0de09492013-03-13 14:37:21 -070083 String dpid;
84 LeaderLatch latch;
85
Jonathan Hart89187372013-03-14 16:41:09 -070086 public SwitchLeaderListener(String dpid, LeaderLatch latch){
Jonathan Hart0de09492013-03-13 14:37:21 -070087 this.dpid = dpid;
88 this.latch = latch;
89 }
90
91 @Override
92 public void leaderLatchEvent(CuratorFramework arg0,
93 LeaderLatchEvent arg1) {
Jonathan Hart89187372013-03-14 16:41:09 -070094 log.debug("Leadership changed for {}, now {}",
Jonathan Hart0de09492013-03-13 14:37:21 -070095 dpid, latch.hasLeadership());
96
Jonathan Hart89187372013-03-14 16:41:09 -070097 //Check that the leadership request is still active - the client
98 //may have since released the request or even begun another request
99 //(this is why we use == to check the object instance is the same)
100 SwitchLeadershipData swData = switches.get(dpid);
101 if (swData != null && swData.getLatch() == latch){
102 swData.getCallback().controlChanged(
103 HexString.toLong(dpid), latch.hasLeadership());
104 }
105 else {
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700106 log.debug("Latch for {} has changed: old latch {} - new latch {}",
107 new Object[]{dpid, latch, swData.getLatch()});
Jonathan Hart89187372013-03-14 16:41:09 -0700108 }
Jonathan Hart0de09492013-03-13 14:37:21 -0700109 }
110 }
111
Naoki Shiotad00accf2013-06-25 14:40:37 -0700112 protected class SwitchPathCacheListener implements PathChildrenCacheListener {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800113 @Override
114 public void childEvent(CuratorFramework client,
115 PathChildrenCacheEvent event) throws Exception {
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700116 //log.debug("Root switch path cache got {} event", event.getType());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800117
118 String strSwitch = null;
119 if (event.getData() != null){
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800120 String[] splitted = event.getData().getPath().split("/");
121 strSwitch = splitted[splitted.length - 1];
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800122 }
123
124 switch (event.getType()){
125 case CHILD_ADDED:
126 case CHILD_UPDATED:
127 //Check we have a PathChildrenCache for this child, add one if not
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700128 synchronized (switchPathCaches){
129 if (switchPathCaches.get(strSwitch) == null){
130 PathChildrenCache pc = new PathChildrenCache(client,
131 event.getData().getPath(), true);
132 pc.start(StartMode.NORMAL);
133 switchPathCaches.put(strSwitch, pc);
134 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800135 }
136 break;
137 case CHILD_REMOVED:
138 //Remove our PathChildrenCache for this child
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700139 PathChildrenCache pc = null;
140 synchronized(switchPathCaches){
141 pc = switchPathCaches.remove(strSwitch);
142 }
143 if (pc != null){
144 pc.close();
145 }
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800146 break;
147 default:
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700148 //All other events are connection status events. We don't need to
149 //do anything as the path cache handles these on its own.
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800150 break;
151 }
152
153 }
154 };
Naoki Shiotad00accf2013-06-25 14:40:37 -0700155 /**
156 * Listens for changes to the switch znodes in Zookeeper. This maintains
157 * the second level of PathChildrenCaches that hold the controllers
158 * contending for each switch - there's one for each switch.
159 */
160 PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700161 protected ServiceDiscovery<ControllerService> serviceDiscovery;
162 protected ServiceCache<ControllerService> serviceCache;
Jonathan Hartedd6a442013-02-20 15:22:06 -0800163
Jonathan Hartbd181b62013-02-17 16:05:38 -0800164
165 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800166 public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800167 log.info("Requesting control for {}", HexString.toHexString(dpid));
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800168
Jonathan Hartbd766972013-02-22 15:13:03 -0800169 if (controllerId == null){
170 throw new RuntimeException("Must register a controller before calling requestControl");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800171 }
172
173 String dpidStr = HexString.toHexString(dpid);
174 String latchPath = switchLatchesPath + "/" + dpidStr;
175
Jonathan Hart89187372013-03-14 16:41:09 -0700176 if (switches.get(dpidStr) != null){
Jonathan Hart3c0eccd2013-03-12 22:32:50 -0700177 log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
Pankaj Berdeda7187b2013-03-18 15:24:59 -0700178 throw new RegistryException("Already contesting control for " + dpidStr);
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800179 }
180
Jonathan Hartbd766972013-02-22 15:13:03 -0800181 LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
Jonathan Hart89187372013-03-14 16:41:09 -0700182 latch.addListener(new SwitchLeaderListener(dpidStr, latch));
Jonathan Hartbd181b62013-02-17 16:05:38 -0800183
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700184
Jonathan Hart89187372013-03-14 16:41:09 -0700185 SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb);
186 SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
187
188 if (oldData != null){
189 //There was already data for that key in the map
190 //i.e. someone else got here first so we can't succeed
191 log.debug("Already requested control for {}", dpidStr);
192 throw new RegistryException("Already requested control for " + dpidStr);
193 }
194
195 //Now that we know we were able to add our latch to the collection,
Jonathan Hart44e56fc2013-03-14 16:53:59 -0700196 //we can start the leader election in Zookeeper. However I don't know
197 //how to handle if the start fails - the latch is already in our
198 //switches list.
199 //TODO seems like there's a Curator bug when latch.start is called when
200 //there's no Zookeeper connection which causes two znodes to be put in
201 //Zookeeper at the latch path when we reconnect to Zookeeper.
Jonathan Hartbd181b62013-02-17 16:05:38 -0800202 try {
Jonathan Hartbd181b62013-02-17 16:05:38 -0800203 latch.start();
204 } catch (Exception e) {
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800205 log.warn("Error starting leader latch: {}", e.getMessage());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800206 throw new RegistryException("Error starting leader latch for " + dpidStr, e);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800207 }
208
209 }
210
211 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800212 public void releaseControl(long dpid) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800213 log.info("Releasing control for {}", HexString.toHexString(dpid));
Jonathan Hart57080fb2013-02-21 10:55:46 -0800214
Jonathan Hartc6eee9e2013-02-18 14:58:27 -0800215 String dpidStr = HexString.toHexString(dpid);
216
Jonathan Hart89187372013-03-14 16:41:09 -0700217 SwitchLeadershipData swData = switches.remove(dpidStr);
218
219 if (swData == null) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800220 log.debug("Trying to release control of a switch we are not contesting");
Jonathan Hartbd181b62013-02-17 16:05:38 -0800221 return;
222 }
Jonathan Hart89187372013-03-14 16:41:09 -0700223
Jonathan Hart89187372013-03-14 16:41:09 -0700224 LeaderLatch latch = swData.getLatch();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800225
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700226 latch.removeAllListeners();
227
Jonathan Hartbd181b62013-02-17 16:05:38 -0800228 try {
229 latch.close();
230 } catch (IOException e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800231 //I think it's OK not to do anything here. Either the node got
232 //deleted correctly, or the connection went down and the node got deleted.
Umesh Krishnaswamy0ef75ee2013-03-25 17:50:27 -0700233 log.debug("releaseControl: caught IOException {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800234 }
235 }
236
237 @Override
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800238 public boolean hasControl(long dpid) {
Jonathan Hart89187372013-03-14 16:41:09 -0700239 String dpidStr = HexString.toHexString(dpid);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800240
Jonathan Hart89187372013-03-14 16:41:09 -0700241 SwitchLeadershipData swData = switches.get(dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800242
Jonathan Hart89187372013-03-14 16:41:09 -0700243 if (swData == null) {
244 log.warn("No leader latch for dpid {}", dpidStr);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800245 return false;
246 }
247
Jonathan Hart89187372013-03-14 16:41:09 -0700248 return swData.getLatch().hasLeadership();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800249 }
250
251 @Override
Jonathan Hart7bf62172013-02-28 13:17:18 -0800252 public String getControllerId() {
Jonathan Hartbd766972013-02-22 15:13:03 -0800253 return controllerId;
Jonathan Hartbd181b62013-02-17 16:05:38 -0800254 }
255
Jonathan Hartedd6a442013-02-20 15:22:06 -0800256 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800257 public Collection<String> getAllControllers() throws RegistryException {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800258 log.debug("Getting all controllers");
Jonathan Hart1be46262013-02-20 16:43:51 -0800259
Jonathan Hartedd6a442013-02-20 15:22:06 -0800260 List<String> controllers = new ArrayList<String>();
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700261 for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()){
262 String id = instance.getPayload().getControllerId();
263 if (!controllers.contains(id)){
264 controllers.add(id);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800265 }
Jonathan Hartedd6a442013-02-20 15:22:06 -0800266 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700267
Jonathan Hartedd6a442013-02-20 15:22:06 -0800268 return controllers;
269 }
270
271 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800272 public void registerController(String id) throws RegistryException {
Jonathan Hartd10008d2013-02-23 17:04:08 -0800273 if (controllerId != null) {
274 throw new RegistryException(
275 "Controller already registered with id " + controllerId);
276 }
Jonathan Hartbd766972013-02-22 15:13:03 -0800277
278 controllerId = id;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800279
Jonathan Hartedd6a442013-02-20 15:22:06 -0800280 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700281 ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
282 .name(CONTROLLER_SERVICE_NAME)
283 .payload(new ControllerService(controllerId))
284 //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
285 //.uriSpec(uriSpec)
286 .build();
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700287
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700288 serviceDiscovery.registerService(thisInstance);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800289 } catch (Exception e) {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700290 // TODO Auto-generated catch block
291 e.printStackTrace();
Jonathan Hartedd6a442013-02-20 15:22:06 -0800292 }
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700293
Jonathan Hartedd6a442013-02-20 15:22:06 -0800294 }
295
296 @Override
Jonathan Hart57080fb2013-02-21 10:55:46 -0800297 public String getControllerForSwitch(long dpid) throws RegistryException {
Jonathan Hart89187372013-03-14 16:41:09 -0700298 String dpidStr = HexString.toHexString(dpid);
Pankaj Berde017960a2013-03-14 20:32:26 -0700299
Jonathan Hart599c6b32013-03-24 22:42:02 -0700300 PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
301
302 if (switchCache == null){
Jonathan Hartedd6a442013-02-20 15:22:06 -0800303 log.warn("Tried to get controller for non-existent switch");
304 return null;
305 }
306
Jonathan Hartf4e80842013-03-26 23:55:02 -0700307 try {
308 //We've seen issues with these caches get stuck out of date, so we'll have to
309 //force them to refresh before each read. This slows down the method as it
310 //blocks on a Zookeeper query, however at the moment only the cleanup thread
311 //uses this and that isn't particularly time-sensitive.
312 switchCache.rebuild();
313 } catch (Exception e) {
314 // TODO Auto-generated catch block
315 e.printStackTrace();
316 }
317
Jonathan Hart599c6b32013-03-24 22:42:02 -0700318 List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
Jonathan Hart0b3eee42013-03-16 18:20:04 -0700319
Jonathan Hart599c6b32013-03-24 22:42:02 -0700320 Collections.sort(
321 sortedData,
322 new Comparator<ChildData>(){
323 private String getSequenceNumber(String path){
324 return path.substring(path.lastIndexOf('-') + 1);
325 }
326 @Override
327 public int compare(ChildData lhs, ChildData rhs) {
328 return getSequenceNumber(lhs.getPath()).
329 compareTo(getSequenceNumber(rhs.getPath()));
330 }
331 }
332 );
Jonathan Hartedd6a442013-02-20 15:22:06 -0800333
Jonathan Hart56b296e2013-03-25 13:30:10 -0700334 if (sortedData.size() == 0){
335 return null;
336 }
337
Jonathan Hart599c6b32013-03-24 22:42:02 -0700338 return new String(sortedData.get(0).getData(), Charsets.UTF_8);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800339 }
340
341 @Override
342 public Collection<Long> getSwitchesControlledByController(String controllerId) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800343 //TODO remove this if not needed
Jonathan Hartbd766972013-02-22 15:13:03 -0800344 throw new RuntimeException("Not yet implemented");
Jonathan Hartedd6a442013-02-20 15:22:06 -0800345 }
Jonathan Hartbd181b62013-02-17 16:05:38 -0800346
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800347
Jonathan Hart89187372013-03-14 16:41:09 -0700348 //TODO what should happen when there's no ZK connection? Currently we just return
349 //the cache but this may lead to false impressions - i.e. we don't actually know
350 //what's in ZK so we shouldn't say we do
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800351 @Override
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800352 public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
353 Map<String, List<ControllerRegistryEntry>> data =
354 new HashMap<String, List<ControllerRegistryEntry>>();
355
356 for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()){
357 List<ControllerRegistryEntry> contendingControllers =
358 new ArrayList<ControllerRegistryEntry>();
359
360 if (entry.getValue().getCurrentData().size() < 1){
Jonathan Hartcbb4b952013-03-18 16:15:18 -0700361 //TODO prevent even having the PathChildrenCache in this case
362 //log.info("Switch entry with no leader elections: {}", entry.getKey());
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800363 continue;
364 }
365
366 for (ChildData d : entry.getValue().getCurrentData()) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800367
Jonathan Hartd10008d2013-02-23 17:04:08 -0800368 String controllerId = new String(d.getData(), Charsets.UTF_8);
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800369
370 String[] splitted = d.getPath().split("-");
371 int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
372
373 contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
374 }
375
376 Collections.sort(contendingControllers);
377 data.put(entry.getKey(), contendingControllers);
378 }
379 return data;
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800380 }
381
Naoki Shiotaa3b2dfa2013-06-27 13:52:24 -0700382 /**
383 * Returns a block of IDs which are unique and unused.
384 * Range of IDs is fixed size and is assigned incrementally as this method called.
385 * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
386 * requests come up simultaneously.
387 */
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700388 public IdBlock allocateUniqueIdBlock(){
389 try {
390 AtomicValue<Long> result = null;
391 do {
392 result = distributedIdCounter.add(ID_BLOCK_SIZE);
393 } while (result == null || !result.succeeded());
394
395 return new IdBlock(result.preValue(), result.postValue() - 1, ID_BLOCK_SIZE);
396 } catch (Exception e) {
397 log.error("Error allocating ID block");
398 }
399
400 return null;
401 }
402
Jonathan Hartbd181b62013-02-17 16:05:38 -0800403 /*
404 * IFloodlightModule
405 */
406
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800407 @Override
408 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hartedd6a442013-02-20 15:22:06 -0800409 Collection<Class<? extends IFloodlightService>> l =
410 new ArrayList<Class<? extends IFloodlightService>>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800411 l.add(IControllerRegistryService.class);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800412 return l;
413 }
414
415 @Override
416 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
417 Map<Class<? extends IFloodlightService>, IFloodlightService> m =
418 new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800419 m.put(IControllerRegistryService.class, this);
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800420 return m;
421 }
422
423 @Override
424 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800425 Collection<Class<? extends IFloodlightService>> l =
426 new ArrayList<Class<? extends IFloodlightService>>();
427 l.add(IRestApiService.class);
428 return l;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800429 }
430
Jonathan Hart89187372013-03-14 16:41:09 -0700431 //TODO currently blocks startup when it can't get a Zookeeper connection.
432 //Do we support starting up with no Zookeeper connection?
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800433 @Override
434 public void init (FloodlightModuleContext context) throws FloodlightModuleException {
Jonathan Hartbd766972013-02-22 15:13:03 -0800435 log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
436
Jonathan Hart97801ac2013-02-26 14:29:16 -0800437 //Read the Zookeeper connection string from the config
438 Map<String, String> configParams = context.getConfigParams(this);
439 String connectionString = configParams.get("connectionString");
440 if (connectionString != null){
441 this.connectionString = connectionString;
Jonathan Hart57080fb2013-02-21 10:55:46 -0800442 }
Jonathan Hart97801ac2013-02-26 14:29:16 -0800443 log.info("Setting Zookeeper connection string to {}", this.connectionString);
Jonathan Hart57080fb2013-02-21 10:55:46 -0800444
Jonathan Hart97801ac2013-02-26 14:29:16 -0800445 restApi = context.getServiceImpl(IRestApiService.class);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800446
Jonathan Hart89187372013-03-14 16:41:09 -0700447 switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
Jonathan Hart4baf3be2013-03-21 18:26:13 -0700448 //switchPathCaches = new HashMap<String, PathChildrenCache>();
449 switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800450
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800451 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800452 client = CuratorFrameworkFactory.newClient(this.connectionString,
Jonathan Hartcc957a02013-02-26 10:39:04 -0800453 sessionTimeout, connectionTimeout, retryPolicy);
Jonathan Hartbd181b62013-02-17 16:05:38 -0800454
455 client.start();
Jonathan Hartbd181b62013-02-17 16:05:38 -0800456 client = client.usingNamespace(namespace);
Jonathan Hart97801ac2013-02-26 14:29:16 -0800457
Jonathan Hart1530ccc2013-04-03 19:36:02 -0700458 distributedIdCounter = new DistributedAtomicLong(
459 client,
460 ID_COUNTER_PATH,
461 new RetryOneTime(100));
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800462
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800463 switchCache = new PathChildrenCache(client, switchLatchesPath, true);
464 switchCache.getListenable().addListener(switchPathCacheListener);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800465
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700466 //Build the service discovery object
467 serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
468 .client(client).basePath(SERVICES_PATH).build();
469
470 //We read the list of services very frequently (GUI periodically queries them)
471 //so we'll cache them to cut down on Zookeeper queries.
472 serviceCache = serviceDiscovery.serviceCacheBuilder()
473 .name(CONTROLLER_SERVICE_NAME).build();
474
475
Jonathan Hartedd6a442013-02-20 15:22:06 -0800476 try {
Jonathan Hart71c0ffc2013-03-24 15:58:42 -0700477 serviceDiscovery.start();
478 serviceCache.start();
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800479
480 //Don't prime the cache, we want a notification for each child node in the path
481 switchCache.start(StartMode.NORMAL);
Jonathan Hartedd6a442013-02-20 15:22:06 -0800482 } catch (Exception e) {
Jonathan Hart7bf62172013-02-28 13:17:18 -0800483 throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
484 + e.getMessage());
Jonathan Hartedd6a442013-02-20 15:22:06 -0800485 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800486 }
487
488 @Override
489 public void startUp (FloodlightModuleContext context) {
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800490 restApi.addRestletRoutable(new RegistryWebRoutable());
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800491 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800492}