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