blob: 884df0e2d91b89ed7a4877a4b9478d34e378ac31 [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 Milkey269ffb92014-04-03 14:43:30 -070059 protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
60 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
90 protected static final int sessionTimeout = 5000;
91 protected static final int connectionTimeout = 7000;
92
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;
142 LeaderLatch latch;
Jonathan Hart116b1fe2014-03-14 18:53:47 -0700143
Ray Milkey269ffb92014-04-03 14:43:30 -0700144 public SwitchLeaderListener(String dpid, LeaderLatch latch) {
145 this.dpid = dpid;
146 this.latch = latch;
147 }
Jonathan Hart116b1fe2014-03-14 18:53:47 -0700148
Ray Milkey269ffb92014-04-03 14:43:30 -0700149 @Override
150 public void isLeader() {
151 log.debug("Became leader for {}", dpid);
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800152
Ray Milkey269ffb92014-04-03 14:43:30 -0700153 switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), true));
154 }
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800155
Ray Milkey269ffb92014-04-03 14:43:30 -0700156 @Override
157 public void notLeader() {
158 log.debug("Lost leadership for {}", dpid);
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800159
Ray Milkey269ffb92014-04-03 14:43:30 -0700160 switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), false));
161 }
162 }
Jonathan Hart116b1fe2014-03-14 18:53:47 -0700163
Ray Milkey269ffb92014-04-03 14:43:30 -0700164 protected class SwitchPathCacheListener implements PathChildrenCacheListener {
165 @Override
166 public void childEvent(CuratorFramework client,
167 PathChildrenCacheEvent event) throws Exception {
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800168
Ray Milkey269ffb92014-04-03 14:43:30 -0700169 String strSwitch = null;
170 if (event.getData() != null) {
171 String[] splitted = event.getData().getPath().split("/");
172 strSwitch = splitted[splitted.length - 1];
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800173 }
Ray Milkey269ffb92014-04-03 14:43:30 -0700174
175 switch (event.getType()) {
176 case CHILD_ADDED:
177 case CHILD_UPDATED:
178 //Check we have a PathChildrenCache for this child, add one if not
179 synchronized (switchPathCaches) {
180 if (switchPathCaches.get(strSwitch) == null) {
181 PathChildrenCache pc = new PathChildrenCache(client,
182 event.getData().getPath(), true);
183 pc.start(StartMode.NORMAL);
184 switchPathCaches.put(strSwitch, pc);
185 }
186 }
187 break;
188 case CHILD_REMOVED:
189 //Remove our PathChildrenCache for this child
190 PathChildrenCache pc = null;
191 synchronized (switchPathCaches) {
192 pc = switchPathCaches.remove(strSwitch);
193 }
194 if (pc != null) {
195 pc.close();
196 }
197 break;
198 default:
199 //All other switchLeadershipEvents are connection status switchLeadershipEvents. We don't need to
200 //do anything as the path cache handles these on its own.
201 break;
202 }
203
204 }
205 }
206
207 ;
208
209 protected class ClusterLeaderListener implements LeaderLatchListener {
210 LeaderLatch latch;
211
212 public ClusterLeaderListener(LeaderLatch latch) {
213 this.latch = latch;
214 }
215
216 //
217 // NOTE: If we need to support callbacks when the
218 // leadership changes, those should be called here.
219 //
220
221 @Override
222 public void isLeader() {
223 log.debug("Cluster leadership aquired");
224 }
225
226 @Override
227 public void notLeader() {
228 log.debug("Cluster leadership lost");
229 }
230 }
231
232 /**
233 * Listens for changes to the switch znodes in Zookeeper. This maintains
234 * the second level of PathChildrenCaches that hold the controllers
235 * contending for each switch - there's one for each switch.
236 */
237 PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
238 protected ServiceDiscovery<ControllerService> serviceDiscovery;
239 protected ServiceCache<ControllerService> serviceCache;
240
241
242 @Override
243 public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
244 log.info("Requesting control for {}", HexString.toHexString(dpid));
245
246 if (controllerId == null) {
247 throw new RuntimeException("Must register a controller before calling requestControl");
248 }
249
250 String dpidStr = HexString.toHexString(dpid);
251 String latchPath = switchLatchesPath + "/" + dpidStr;
252
253 if (switches.get(dpidStr) != null) {
254 log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
255 throw new RegistryException("Already contesting control for " + dpidStr);
256 }
257
258 LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
259 SwitchLeaderListener listener = new SwitchLeaderListener(dpidStr, latch);
260 latch.addListener(listener);
261
262
263 SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb, listener);
264 SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
265
266 if (oldData != null) {
267 //There was already data for that key in the map
268 //i.e. someone else got here first so we can't succeed
269 log.debug("Already requested control for {}", dpidStr);
270 throw new RegistryException("Already requested control for " + dpidStr);
271 }
272
273 //Now that we know we were able to add our latch to the collection,
274 //we can start the leader election in Zookeeper. However I don't know
275 //how to handle if the start fails - the latch is already in our
276 //switches list.
277 //TODO seems like there's a Curator bug when latch.start is called when
278 //there's no Zookeeper connection which causes two znodes to be put in
279 //Zookeeper at the latch path when we reconnect to Zookeeper.
280 try {
281 latch.start();
282 } catch (Exception e) {
283 log.warn("Error starting leader latch: {}", e.getMessage());
284 throw new RegistryException("Error starting leader latch for " + dpidStr, e);
285 }
286
287 }
288
289 @Override
290 public void releaseControl(long dpid) {
291 log.info("Releasing control for {}", HexString.toHexString(dpid));
292
293 String dpidStr = HexString.toHexString(dpid);
294
295 SwitchLeadershipData swData = switches.remove(dpidStr);
296
297 if (swData == null) {
298 log.debug("Trying to release control of a switch we are not contesting");
299 return;
300 }
301
302 LeaderLatch latch = swData.getLatch();
303
304 latch.removeListener(swData.getListener());
305
306 try {
307 latch.close();
308 } catch (IOException e) {
309 //I think it's OK not to do anything here. Either the node got
310 //deleted correctly, or the connection went down and the node got deleted.
311 log.debug("releaseControl: caught IOException {}", dpidStr);
312 }
313 }
314
315 @Override
316 public boolean hasControl(long dpid) {
317 String dpidStr = HexString.toHexString(dpid);
318
319 SwitchLeadershipData swData = switches.get(dpidStr);
320
321 if (swData == null) {
322 log.warn("No leader latch for dpid {}", dpidStr);
323 return false;
324 }
325
326 return swData.getLatch().hasLeadership();
327 }
328
329 @Override
330 public boolean isClusterLeader() {
331 return clusterLeaderLatch.hasLeadership();
332 }
333
334 @Override
335 public String getControllerId() {
336 return controllerId;
337 }
338
339 @Override
340 public Collection<String> getAllControllers() throws RegistryException {
341 log.debug("Getting all controllers");
342
343 List<String> controllers = new ArrayList<String>();
344 for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()) {
345 String id = instance.getPayload().getControllerId();
346 if (!controllers.contains(id)) {
347 controllers.add(id);
348 }
349 }
350
351 return controllers;
352 }
353
354 @Override
355 public void registerController(String id) throws RegistryException {
356 if (controllerId != null) {
357 throw new RegistryException(
358 "Controller already registered with id " + controllerId);
359 }
360
361 controllerId = id;
362
363 try {
364 ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
365 .name(CONTROLLER_SERVICE_NAME)
366 .payload(new ControllerService(controllerId))
367 //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
368 //.uriSpec(uriSpec)
369 .build();
370
371 serviceDiscovery.registerService(thisInstance);
372 } catch (Exception e) {
373 // TODO Auto-generated catch block
374 e.printStackTrace();
375 }
376
377 }
378
379 @Override
380 public String getControllerForSwitch(long dpid) throws RegistryException {
381 String dpidStr = HexString.toHexString(dpid);
382
383 PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
384
385 if (switchCache == null) {
386 log.warn("Tried to get controller for non-existent switch");
Nick Karanatsios8abe7172014-02-19 20:31:48 -0800387 return null;
388 }
Pavlin Radoslavov52163ed2014-03-19 11:39:34 -0700389
Ray Milkey269ffb92014-04-03 14:43:30 -0700390 try {
391 //We've seen issues with these caches get stuck out of date, so we'll have to
392 //force them to refresh before each read. This slows down the method as it
393 //blocks on a Zookeeper query, however at the moment only the cleanup thread
394 //uses this and that isn't particularly time-sensitive.
395 switchCache.rebuild();
396 } catch (Exception e) {
397 // TODO Auto-generated catch block
398 e.printStackTrace();
399 }
Pavlin Radoslavov52163ed2014-03-19 11:39:34 -0700400
Ray Milkey269ffb92014-04-03 14:43:30 -0700401 List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
402
403 Collections.sort(
404 sortedData,
405 new Comparator<ChildData>() {
406 private String getSequenceNumber(String path) {
407 return path.substring(path.lastIndexOf('-') + 1);
408 }
409
410 @Override
411 public int compare(ChildData lhs, ChildData rhs) {
412 return getSequenceNumber(lhs.getPath()).
413 compareTo(getSequenceNumber(rhs.getPath()));
414 }
415 }
416 );
417
418 if (sortedData.size() == 0) {
419 return null;
420 }
421
422 return new String(sortedData.get(0).getData(), Charsets.UTF_8);
423 }
424
425 @Override
426 public Collection<Long> getSwitchesControlledByController(String controllerId) {
427 //TODO remove this if not needed
428 throw new RuntimeException("Not yet implemented");
429 }
430
431
432 //TODO what should happen when there's no ZK connection? Currently we just return
433 //the cache but this may lead to false impressions - i.e. we don't actually know
434 //what's in ZK so we shouldn't say we do
435 @Override
436 public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
437 Map<String, List<ControllerRegistryEntry>> data =
438 new HashMap<String, List<ControllerRegistryEntry>>();
439
440 for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()) {
441 List<ControllerRegistryEntry> contendingControllers =
442 new ArrayList<ControllerRegistryEntry>();
443
444 if (entry.getValue().getCurrentData().size() < 1) {
445 //TODO prevent even having the PathChildrenCache in this case
446 //log.info("Switch entry with no leader elections: {}", entry.getKey());
447 continue;
448 }
449
450 for (ChildData d : entry.getValue().getCurrentData()) {
451
452 String controllerId = new String(d.getData(), Charsets.UTF_8);
453
454 String[] splitted = d.getPath().split("-");
455 int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
456
457 contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
458 }
459
460 Collections.sort(contendingControllers);
461 data.put(entry.getKey(), contendingControllers);
462 }
463 return data;
464 }
465
466 public IdBlock allocateUniqueIdBlock(long range) {
467 try {
468 AtomicValue<Long> result = null;
469 do {
470 result = distributedIdCounter.add(range);
471 } while (result == null || !result.succeeded());
472
473 return new IdBlock(result.preValue(), result.postValue() - 1, range);
474 } catch (Exception e) {
475 log.error("Error allocating ID block");
476 }
477 return null;
478 }
479
480 /**
481 * Returns a block of IDs which are unique and unused.
482 * Range of IDs is fixed size and is assigned incrementally as this method called.
483 * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
484 * requests come up simultaneously.
485 */
486 @Override
487 public IdBlock allocateUniqueIdBlock() {
488 return allocateUniqueIdBlock(ID_BLOCK_SIZE);
489 }
490
491 /**
492 * Get a globally unique ID.
493 *
494 * @return a globally unique ID.
495 */
496 @Override
497 public synchronized long getNextUniqueId() {
498 //
499 // Generate the next Unique ID.
500 //
501 // TODO: For now, the higher 32 bits are random, and
502 // the lower 32 bits are sequential.
503 // The implementation must be updated to use the Zookeeper
504 // to allocate the higher 32 bits (globally unique).
505 //
506 if ((nextUniqueIdSuffix & 0xffffffffL) == 0xffffffffL) {
507 nextUniqueIdPrefix = randomGenerator.nextInt();
508 nextUniqueIdSuffix = 0;
509 } else {
510 nextUniqueIdSuffix++;
511 }
512 long result = (long) nextUniqueIdPrefix << 32;
513 result = result | (0xffffffffL & nextUniqueIdSuffix);
514 return result;
515 }
516
517 /*
518 * IFloodlightModule
519 */
520
521 @Override
522 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
523 Collection<Class<? extends IFloodlightService>> l =
Jonathan Hart3d7730a2013-02-22 11:51:17 -0800524 new ArrayList<Class<? extends IFloodlightService>>();
Ray Milkey269ffb92014-04-03 14:43:30 -0700525 l.add(IControllerRegistryService.class);
526 return l;
527 }
Pavlin Radoslavov52163ed2014-03-19 11:39:34 -0700528
Ray Milkey269ffb92014-04-03 14:43:30 -0700529 @Override
530 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
531 Map<Class<? extends IFloodlightService>, IFloodlightService> m =
532 new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
533 m.put(IControllerRegistryService.class, this);
534 return m;
535 }
Pavlin Radoslavov52163ed2014-03-19 11:39:34 -0700536
Ray Milkey269ffb92014-04-03 14:43:30 -0700537 @Override
538 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
539 Collection<Class<? extends IFloodlightService>> l =
540 new ArrayList<Class<? extends IFloodlightService>>();
541 l.add(IFloodlightProviderService.class);
542 l.add(IRestApiService.class);
543 return l;
544 }
Jonathan Hartbd181b62013-02-17 16:05:38 -0800545
Ray Milkey269ffb92014-04-03 14:43:30 -0700546 //TODO currently blocks startup when it can't get a Zookeeper connection.
547 //Do we support starting up with no Zookeeper connection?
548 @Override
549 public void init(FloodlightModuleContext context) throws FloodlightModuleException {
550 log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
Jonathan Hart97801ac2013-02-26 14:29:16 -0800551
Ray Milkey269ffb92014-04-03 14:43:30 -0700552 //Read the Zookeeper connection string from the config
553 Map<String, String> configParams = context.getConfigParams(this);
554 String connectionString = configParams.get("connectionString");
555 if (connectionString != null) {
556 this.connectionString = connectionString;
557 }
558 log.info("Setting Zookeeper connection string to {}", this.connectionString);
Jonathan Hart116b1fe2014-03-14 18:53:47 -0700559
Ray Milkey269ffb92014-04-03 14:43:30 -0700560 //
561 // Initialize the Unique ID generator
562 // TODO: This must be replaced by Zookeeper-based allocation
563 //
564 nextUniqueIdPrefix = randomGenerator.nextInt();
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800565
Ray Milkey269ffb92014-04-03 14:43:30 -0700566 restApi = context.getServiceImpl(IRestApiService.class);
Pavlin Radoslavovf1377ce2014-02-05 17:37:24 -0800567
Ray Milkey269ffb92014-04-03 14:43:30 -0700568 switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
569 //switchPathCaches = new HashMap<String, PathChildrenCache>();
570 switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
571
572 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
573 client = CuratorFrameworkFactory.newClient(this.connectionString,
574 sessionTimeout, connectionTimeout, retryPolicy);
575
576 client.start();
577 client = client.usingNamespace(namespace);
578
579 distributedIdCounter = new DistributedAtomicLong(
580 client,
581 ID_COUNTER_PATH,
582 new RetryOneTime(100));
583
584 switchCache = new PathChildrenCache(client, switchLatchesPath, true);
585 switchCache.getListenable().addListener(switchPathCacheListener);
586
587 //Build the service discovery object
588 serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
589 .client(client).basePath(SERVICES_PATH).build();
590
591 //We read the list of services very frequently (GUI periodically queries them)
592 //so we'll cache them to cut down on Zookeeper queries.
593 serviceCache = serviceDiscovery.serviceCacheBuilder()
594 .name(CONTROLLER_SERVICE_NAME).build();
595
596
597 try {
598 serviceDiscovery.start();
599 serviceCache.start();
600
601 //Don't prime the cache, we want a notification for each child node in the path
602 switchCache.start(StartMode.NORMAL);
603 } catch (Exception e) {
604 throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
605 + e.getMessage());
606 }
607
608 eventThreadExecutorService = Executors.newSingleThreadExecutor();
609 eventThreadExecutorService.execute(
610 new Runnable() {
611 @Override
612 public void run() {
613 dispatchEvents();
614 }
615 });
616 }
617
618 @Override
619 public void startUp(FloodlightModuleContext context) {
620 //
621 // Cluster Leader election setup.
622 // NOTE: We have to do it here, because during the init stage
623 // we don't know the Controller ID.
624 //
625 if (controllerId == null) {
626 log.error("Error on startup: unknown ControllerId");
627 }
628 clusterLeaderLatch = new LeaderLatch(client,
629 CLUSTER_LEADER_PATH,
630 controllerId);
631 clusterLeaderListener = new ClusterLeaderListener(clusterLeaderLatch);
632 clusterLeaderLatch.addListener(clusterLeaderListener);
633 try {
634 clusterLeaderLatch.start();
635 } catch (Exception e) {
636 log.error("Error on startup starting the cluster leader election: {}", e.getMessage());
637 }
638
639 // Keep trying until there is a cluster leader
640 do {
641 try {
642 Participant leader = clusterLeaderLatch.getLeader();
643 if (!leader.getId().isEmpty())
644 break;
645 Thread.sleep(CLUSTER_LEADER_ELECTION_RETRY_MS);
646 } catch (Exception e) {
647 log.error("Error on startup waiting for cluster leader election: {}", e.getMessage());
648 }
649 } while (true);
650
651 restApi.addRestletRoutable(new RegistryWebRoutable());
652 }
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800653}