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