blob: 52b23ce883844e6ec69415d6ec1f40c23f67f309 [file] [log] [blame]
Madan Jampani2ff05592014-10-10 15:42:47 -07001package org.onlab.onos.store.link.impl;
2
3import com.google.common.base.Function;
4import com.google.common.base.Predicate;
5import com.google.common.collect.FluentIterable;
6import com.google.common.collect.HashMultimap;
Madan Jampania97e8202014-10-10 17:01:33 -07007import com.google.common.collect.ImmutableList;
Madan Jampani2ff05592014-10-10 15:42:47 -07008import com.google.common.collect.Maps;
9import com.google.common.collect.SetMultimap;
10
Madan Jampania97e8202014-10-10 17:01:33 -070011import org.apache.commons.lang3.RandomUtils;
Madan Jampani2ff05592014-10-10 15:42:47 -070012import org.apache.commons.lang3.concurrent.ConcurrentUtils;
13import org.apache.felix.scr.annotations.Activate;
14import org.apache.felix.scr.annotations.Component;
15import org.apache.felix.scr.annotations.Deactivate;
16import org.apache.felix.scr.annotations.Reference;
17import org.apache.felix.scr.annotations.ReferenceCardinality;
18import org.apache.felix.scr.annotations.Service;
19import org.onlab.onos.cluster.ClusterService;
Madan Jampania97e8202014-10-10 17:01:33 -070020import org.onlab.onos.cluster.ControllerNode;
21import org.onlab.onos.cluster.NodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070022import org.onlab.onos.net.AnnotationsUtil;
23import org.onlab.onos.net.ConnectPoint;
24import org.onlab.onos.net.DefaultAnnotations;
25import org.onlab.onos.net.DefaultLink;
26import org.onlab.onos.net.DeviceId;
27import org.onlab.onos.net.Link;
28import org.onlab.onos.net.SparseAnnotations;
29import org.onlab.onos.net.Link.Type;
30import org.onlab.onos.net.LinkKey;
31import org.onlab.onos.net.Provided;
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -070032import org.onlab.onos.net.device.DeviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -070033import org.onlab.onos.net.link.DefaultLinkDescription;
34import org.onlab.onos.net.link.LinkDescription;
35import org.onlab.onos.net.link.LinkEvent;
36import org.onlab.onos.net.link.LinkStore;
37import org.onlab.onos.net.link.LinkStoreDelegate;
38import org.onlab.onos.net.provider.ProviderId;
39import org.onlab.onos.store.AbstractStore;
Madan Jampani2ff05592014-10-10 15:42:47 -070040import org.onlab.onos.store.Timestamp;
41import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
42import org.onlab.onos.store.cluster.messaging.ClusterMessage;
43import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
44import org.onlab.onos.store.cluster.messaging.MessageSubject;
45import org.onlab.onos.store.common.impl.Timestamped;
46import org.onlab.onos.store.serializers.DistributedStoreSerializers;
47import org.onlab.onos.store.serializers.KryoSerializer;
48import org.onlab.util.KryoPool;
49import org.onlab.util.NewConcurrentHashMap;
50import org.slf4j.Logger;
51
52import java.io.IOException;
53import java.util.Collections;
Madan Jampania97e8202014-10-10 17:01:33 -070054import java.util.HashMap;
Madan Jampani2ff05592014-10-10 15:42:47 -070055import java.util.HashSet;
56import java.util.Map;
57import java.util.Set;
58import java.util.Map.Entry;
59import java.util.concurrent.ConcurrentHashMap;
60import java.util.concurrent.ConcurrentMap;
Madan Jampania97e8202014-10-10 17:01:33 -070061import java.util.concurrent.ScheduledExecutorService;
62import java.util.concurrent.TimeUnit;
Madan Jampani2ff05592014-10-10 15:42:47 -070063
Madan Jampania97e8202014-10-10 17:01:33 -070064import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
65import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070066import static org.onlab.onos.net.DefaultAnnotations.union;
67import static org.onlab.onos.net.DefaultAnnotations.merge;
68import static org.onlab.onos.net.Link.Type.DIRECT;
69import static org.onlab.onos.net.Link.Type.INDIRECT;
70import static org.onlab.onos.net.link.LinkEvent.Type.*;
Madan Jampania97e8202014-10-10 17:01:33 -070071import static org.onlab.util.Tools.namedThreads;
Madan Jampani2ff05592014-10-10 15:42:47 -070072import static org.slf4j.LoggerFactory.getLogger;
73import static com.google.common.collect.Multimaps.synchronizedSetMultimap;
74import static com.google.common.base.Predicates.notNull;
75
76/**
77 * Manages inventory of infrastructure links in distributed data store
78 * that uses optimistic replication and gossip based techniques.
79 */
80@Component(immediate = true)
81@Service
82public class GossipLinkStore
83 extends AbstractStore<LinkEvent, LinkStoreDelegate>
84 implements LinkStore {
85
86 private final Logger log = getLogger(getClass());
87
88 // Link inventory
89 private final ConcurrentMap<LinkKey, ConcurrentMap<ProviderId, Timestamped<LinkDescription>>> linkDescs =
90 new ConcurrentHashMap<>();
91
92 // Link instance cache
93 private final ConcurrentMap<LinkKey, Link> links = new ConcurrentHashMap<>();
94
95 // Egress and ingress link sets
96 private final SetMultimap<DeviceId, LinkKey> srcLinks = createSynchronizedHashMultiMap();
97 private final SetMultimap<DeviceId, LinkKey> dstLinks = createSynchronizedHashMultiMap();
98
99 // Remove links
100 private final Map<LinkKey, Timestamp> removedLinks = Maps.newHashMap();
101
102 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700103 protected DeviceClockService deviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -0700104
105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
106 protected ClusterCommunicationService clusterCommunicator;
107
108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
109 protected ClusterService clusterService;
110
111 private static final KryoSerializer SERIALIZER = new KryoSerializer() {
112 @Override
113 protected void setupKryoPool() {
114 serializerPool = KryoPool.newBuilder()
115 .register(DistributedStoreSerializers.COMMON)
116 .register(InternalLinkEvent.class)
117 .register(InternalLinkRemovedEvent.class)
Madan Jampanid2054d42014-10-10 17:27:06 -0700118 .register(LinkAntiEntropyAdvertisement.class)
119 .register(LinkFragmentId.class)
Madan Jampani2ff05592014-10-10 15:42:47 -0700120 .build()
121 .populate(1);
122 }
123 };
124
Madan Jampania97e8202014-10-10 17:01:33 -0700125 private ScheduledExecutorService executor;
126
Madan Jampani2ff05592014-10-10 15:42:47 -0700127 @Activate
128 public void activate() {
129
130 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700131 GossipLinkStoreMessageSubjects.LINK_UPDATE,
132 new InternalLinkEventListener());
Madan Jampani2ff05592014-10-10 15:42:47 -0700133 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700134 GossipLinkStoreMessageSubjects.LINK_REMOVED,
135 new InternalLinkRemovedEventListener());
136 clusterCommunicator.addSubscriber(
137 GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT,
138 new InternalLinkAntiEntropyAdvertisementListener());
139
140 executor =
141 newSingleThreadScheduledExecutor(namedThreads("link-anti-entropy-%d"));
142
143 // TODO: Make these configurable
144 long initialDelaySec = 5;
145 long periodSec = 5;
146 // start anti-entropy thread
147 executor.scheduleAtFixedRate(new SendAdvertisementTask(),
148 initialDelaySec, periodSec, TimeUnit.SECONDS);
Madan Jampani2ff05592014-10-10 15:42:47 -0700149
150 log.info("Started");
151 }
152
153 @Deactivate
154 public void deactivate() {
Madan Jampani3ffbb272014-10-13 11:19:37 -0700155
156 executor.shutdownNow();
157 try {
158 if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
159 log.error("Timeout during executor shutdown");
160 }
161 } catch (InterruptedException e) {
162 log.error("Error during executor shutdown", e);
163 }
164
Madan Jampani2ff05592014-10-10 15:42:47 -0700165 linkDescs.clear();
166 links.clear();
167 srcLinks.clear();
168 dstLinks.clear();
169 log.info("Stopped");
170 }
171
172 @Override
173 public int getLinkCount() {
174 return links.size();
175 }
176
177 @Override
178 public Iterable<Link> getLinks() {
179 return Collections.unmodifiableCollection(links.values());
180 }
181
182 @Override
183 public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
184 // lock for iteration
185 synchronized (srcLinks) {
186 return FluentIterable.from(srcLinks.get(deviceId))
187 .transform(lookupLink())
188 .filter(notNull())
189 .toSet();
190 }
191 }
192
193 @Override
194 public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
195 // lock for iteration
196 synchronized (dstLinks) {
197 return FluentIterable.from(dstLinks.get(deviceId))
198 .transform(lookupLink())
199 .filter(notNull())
200 .toSet();
201 }
202 }
203
204 @Override
205 public Link getLink(ConnectPoint src, ConnectPoint dst) {
206 return links.get(new LinkKey(src, dst));
207 }
208
209 @Override
210 public Set<Link> getEgressLinks(ConnectPoint src) {
211 Set<Link> egress = new HashSet<>();
212 for (LinkKey linkKey : srcLinks.get(src.deviceId())) {
213 if (linkKey.src().equals(src)) {
214 egress.add(links.get(linkKey));
215 }
216 }
217 return egress;
218 }
219
220 @Override
221 public Set<Link> getIngressLinks(ConnectPoint dst) {
222 Set<Link> ingress = new HashSet<>();
223 for (LinkKey linkKey : dstLinks.get(dst.deviceId())) {
224 if (linkKey.dst().equals(dst)) {
225 ingress.add(links.get(linkKey));
226 }
227 }
228 return ingress;
229 }
230
231 @Override
232 public LinkEvent createOrUpdateLink(ProviderId providerId,
233 LinkDescription linkDescription) {
234
235 DeviceId dstDeviceId = linkDescription.dst().deviceId();
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700236 Timestamp newTimestamp = deviceClockService.getTimestamp(dstDeviceId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700237
238 final Timestamped<LinkDescription> deltaDesc = new Timestamped<>(linkDescription, newTimestamp);
239
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700240 LinkKey key = new LinkKey(linkDescription.src(), linkDescription.dst());
241 final LinkEvent event;
242 final Timestamped<LinkDescription> mergedDesc;
243 synchronized (getLinkDescriptions(key)) {
244 event = createOrUpdateLinkInternal(providerId, deltaDesc);
245 mergedDesc = getLinkDescriptions(key).get(providerId);
246 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700247
248 if (event != null) {
249 log.info("Notifying peers of a link update topology event from providerId: "
250 + "{} between src: {} and dst: {}",
251 providerId, linkDescription.src(), linkDescription.dst());
252 try {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700253 notifyPeers(new InternalLinkEvent(providerId, mergedDesc));
Madan Jampani2ff05592014-10-10 15:42:47 -0700254 } catch (IOException e) {
255 log.info("Failed to notify peers of a link update topology event from providerId: "
256 + "{} between src: {} and dst: {}",
257 providerId, linkDescription.src(), linkDescription.dst());
258 }
259 }
260 return event;
261 }
262
263 private LinkEvent createOrUpdateLinkInternal(
264 ProviderId providerId,
265 Timestamped<LinkDescription> linkDescription) {
266
267 LinkKey key = new LinkKey(linkDescription.value().src(), linkDescription.value().dst());
268 ConcurrentMap<ProviderId, Timestamped<LinkDescription>> descs = getLinkDescriptions(key);
269
270 synchronized (descs) {
271 // if the link was previously removed, we should proceed if and
272 // only if this request is more recent.
273 Timestamp linkRemovedTimestamp = removedLinks.get(key);
274 if (linkRemovedTimestamp != null) {
275 if (linkDescription.isNewer(linkRemovedTimestamp)) {
276 removedLinks.remove(key);
277 } else {
278 return null;
279 }
280 }
281
282 final Link oldLink = links.get(key);
283 // update description
284 createOrUpdateLinkDescription(descs, providerId, linkDescription);
285 final Link newLink = composeLink(descs);
286 if (oldLink == null) {
287 return createLink(key, newLink);
288 }
289 return updateLink(key, oldLink, newLink);
290 }
291 }
292
293 // Guarded by linkDescs value (=locking each Link)
294 private Timestamped<LinkDescription> createOrUpdateLinkDescription(
295 ConcurrentMap<ProviderId, Timestamped<LinkDescription>> existingLinkDescriptions,
296 ProviderId providerId,
297 Timestamped<LinkDescription> linkDescription) {
298
299 // merge existing attributes and merge
300 Timestamped<LinkDescription> existingLinkDescription = existingLinkDescriptions.get(providerId);
301 if (existingLinkDescription != null && existingLinkDescription.isNewer(linkDescription)) {
302 return null;
303 }
304 Timestamped<LinkDescription> newLinkDescription = linkDescription;
305 if (existingLinkDescription != null) {
306 SparseAnnotations merged = union(existingLinkDescription.value().annotations(),
307 linkDescription.value().annotations());
308 newLinkDescription = new Timestamped<LinkDescription>(
309 new DefaultLinkDescription(
310 linkDescription.value().src(),
311 linkDescription.value().dst(),
312 linkDescription.value().type(), merged),
313 linkDescription.timestamp());
314 }
315 return existingLinkDescriptions.put(providerId, newLinkDescription);
316 }
317
318 // Creates and stores the link and returns the appropriate event.
319 // Guarded by linkDescs value (=locking each Link)
320 private LinkEvent createLink(LinkKey key, Link newLink) {
321
322 if (newLink.providerId().isAncillary()) {
323 // TODO: revisit ancillary only Link handling
324
325 // currently treating ancillary only as down (not visible outside)
326 return null;
327 }
328
329 links.put(key, newLink);
330 srcLinks.put(newLink.src().deviceId(), key);
331 dstLinks.put(newLink.dst().deviceId(), key);
332 return new LinkEvent(LINK_ADDED, newLink);
333 }
334
335 // Updates, if necessary the specified link and returns the appropriate event.
336 // Guarded by linkDescs value (=locking each Link)
337 private LinkEvent updateLink(LinkKey key, Link oldLink, Link newLink) {
338
339 if (newLink.providerId().isAncillary()) {
340 // TODO: revisit ancillary only Link handling
341
342 // currently treating ancillary only as down (not visible outside)
343 return null;
344 }
345
346 if ((oldLink.type() == INDIRECT && newLink.type() == DIRECT) ||
347 !AnnotationsUtil.isEqual(oldLink.annotations(), newLink.annotations())) {
348
349 links.put(key, newLink);
350 // strictly speaking following can be ommitted
351 srcLinks.put(oldLink.src().deviceId(), key);
352 dstLinks.put(oldLink.dst().deviceId(), key);
353 return new LinkEvent(LINK_UPDATED, newLink);
354 }
355 return null;
356 }
357
358 @Override
359 public LinkEvent removeLink(ConnectPoint src, ConnectPoint dst) {
360 final LinkKey key = new LinkKey(src, dst);
361
362 DeviceId dstDeviceId = dst.deviceId();
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700363 Timestamp timestamp = deviceClockService.getTimestamp(dstDeviceId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700364
365 LinkEvent event = removeLinkInternal(key, timestamp);
366
367 if (event != null) {
368 log.info("Notifying peers of a link removed topology event for a link "
369 + "between src: {} and dst: {}", src, dst);
370 try {
371 notifyPeers(new InternalLinkRemovedEvent(key, timestamp));
372 } catch (IOException e) {
373 log.error("Failed to notify peers of a link removed topology event for a link "
374 + "between src: {} and dst: {}", src, dst);
375 }
376 }
377 return event;
378 }
379
380 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
381 ConcurrentMap<ProviderId, Timestamped<LinkDescription>> linkDescriptions =
382 getLinkDescriptions(key);
383 synchronized (linkDescriptions) {
384 // accept removal request if given timestamp is newer than
385 // the latest Timestamp from Primary provider
386 ProviderId primaryProviderId = pickPrimaryProviderId(linkDescriptions);
387 if (linkDescriptions.get(primaryProviderId).isNewer(timestamp)) {
388 return null;
389 }
390 removedLinks.put(key, timestamp);
391 Link link = links.remove(key);
392 linkDescriptions.clear();
393 if (link != null) {
394 srcLinks.remove(link.src().deviceId(), key);
395 dstLinks.remove(link.dst().deviceId(), key);
396 return new LinkEvent(LINK_REMOVED, link);
397 }
398 return null;
399 }
400 }
401
402 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
403 return synchronizedSetMultimap(HashMultimap.<K, V>create());
404 }
405
406 /**
407 * @return primary ProviderID, or randomly chosen one if none exists
408 */
409 private ProviderId pickPrimaryProviderId(
410 ConcurrentMap<ProviderId, Timestamped<LinkDescription>> providerDescs) {
411
412 ProviderId fallBackPrimary = null;
413 for (Entry<ProviderId, Timestamped<LinkDescription>> e : providerDescs.entrySet()) {
414 if (!e.getKey().isAncillary()) {
415 return e.getKey();
416 } else if (fallBackPrimary == null) {
417 // pick randomly as a fallback in case there is no primary
418 fallBackPrimary = e.getKey();
419 }
420 }
421 return fallBackPrimary;
422 }
423
424 private Link composeLink(ConcurrentMap<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
425 ProviderId primaryProviderId = pickPrimaryProviderId(linkDescriptions);
426 Timestamped<LinkDescription> base = linkDescriptions.get(primaryProviderId);
427
428 ConnectPoint src = base.value().src();
429 ConnectPoint dst = base.value().dst();
430 Type type = base.value().type();
431 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
432 annotations = merge(annotations, base.value().annotations());
433
434 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
435 if (primaryProviderId.equals(e.getKey())) {
436 continue;
437 }
438
439 // TODO: should keep track of Description timestamp
440 // and only merge conflicting keys when timestamp is newer
441 // Currently assuming there will never be a key conflict between
442 // providers
443
444 // annotation merging. not so efficient, should revisit later
445 annotations = merge(annotations, e.getValue().value().annotations());
446 }
447
448 return new DefaultLink(primaryProviderId , src, dst, type, annotations);
449 }
450
451 private ConcurrentMap<ProviderId, Timestamped<LinkDescription>> getLinkDescriptions(LinkKey key) {
452 return ConcurrentUtils.createIfAbsentUnchecked(linkDescs, key,
453 NewConcurrentHashMap.<ProviderId, Timestamped<LinkDescription>>ifNeeded());
454 }
455
Madan Jampania97e8202014-10-10 17:01:33 -0700456 private Timestamped<LinkDescription> getLinkDescription(LinkKey key, ProviderId providerId) {
457 return getLinkDescriptions(key).get(providerId);
458 }
459
Madan Jampani2ff05592014-10-10 15:42:47 -0700460 private final Function<LinkKey, Link> lookupLink = new LookupLink();
461 private Function<LinkKey, Link> lookupLink() {
462 return lookupLink;
463 }
464
465 private final class LookupLink implements Function<LinkKey, Link> {
466 @Override
467 public Link apply(LinkKey input) {
468 return links.get(input);
469 }
470 }
471
472 private static final Predicate<Provided> IS_PRIMARY = new IsPrimary();
473 private static final Predicate<Provided> isPrimary() {
474 return IS_PRIMARY;
475 }
476
477 private static final class IsPrimary implements Predicate<Provided> {
478
479 @Override
480 public boolean apply(Provided input) {
481 return !input.providerId().isAncillary();
482 }
483 }
484
485 private void notifyDelegateIfNotNull(LinkEvent event) {
486 if (event != null) {
487 notifyDelegate(event);
488 }
489 }
490
491 // TODO: should we be throwing exception?
492 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
493 ClusterMessage message = new ClusterMessage(
494 clusterService.getLocalNode().id(),
495 subject,
496 SERIALIZER.encode(event));
497 clusterCommunicator.broadcast(message);
498 }
499
Madan Jampania97e8202014-10-10 17:01:33 -0700500 // TODO: should we be throwing exception?
501 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) {
502 try {
503 ClusterMessage message = new ClusterMessage(
504 clusterService.getLocalNode().id(),
505 subject,
506 SERIALIZER.encode(event));
507 clusterCommunicator.unicast(message, recipient);
508 } catch (IOException e) {
509 log.error("Failed to send a {} message to {}", subject.value(), recipient);
510 }
511 }
512
Madan Jampani2ff05592014-10-10 15:42:47 -0700513 private void notifyPeers(InternalLinkEvent event) throws IOException {
514 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
515 }
516
517 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
518 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
519 }
520
Madan Jampania97e8202014-10-10 17:01:33 -0700521 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
522 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
523 }
524
525 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
526 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
527 }
528
529 private final class SendAdvertisementTask implements Runnable {
530
531 @Override
532 public void run() {
533 if (Thread.currentThread().isInterrupted()) {
534 log.info("Interrupted, quitting");
535 return;
536 }
537
538 try {
539 final NodeId self = clusterService.getLocalNode().id();
540 Set<ControllerNode> nodes = clusterService.getNodes();
541
542 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
543 .transform(toNodeId())
544 .toList();
545
546 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -0700547 log.debug("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700548 return;
549 }
550
551 NodeId peer;
552 do {
553 int idx = RandomUtils.nextInt(0, nodeIds.size());
554 peer = nodeIds.get(idx);
555 } while (peer.equals(self));
556
557 LinkAntiEntropyAdvertisement ad = createAdvertisement();
558
559 if (Thread.currentThread().isInterrupted()) {
560 log.info("Interrupted, quitting");
561 return;
562 }
563
564 try {
565 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
566 } catch (Exception e) {
567 log.error("Failed to send anti-entropy advertisement", e);
568 return;
569 }
570 } catch (Exception e) {
571 // catch all Exception to avoid Scheduled task being suppressed.
572 log.error("Exception thrown while sending advertisement", e);
573 }
574 }
575 }
576
577 private LinkAntiEntropyAdvertisement createAdvertisement() {
578 final NodeId self = clusterService.getLocalNode().id();
579
580 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
581 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
582
583 for (Entry<LinkKey, ConcurrentMap<ProviderId, Timestamped<LinkDescription>>>
584 provs : linkDescs.entrySet()) {
585
586 final LinkKey linkKey = provs.getKey();
587 final ConcurrentMap<ProviderId, Timestamped<LinkDescription>> linkDesc = provs.getValue();
588 synchronized (linkDesc) {
589 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
590 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
591 }
592 }
593 }
594
595 linkTombstones.putAll(removedLinks);
596
597 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
598 }
599
600 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement advertisement) {
601
602 NodeId peer = advertisement.sender();
603
604 Map<LinkFragmentId, Timestamp> linkTimestamps = advertisement.linkTimestamps();
605 Map<LinkKey, Timestamp> linkTombstones = advertisement.linkTombstones();
606 for (Map.Entry<LinkFragmentId, Timestamp> entry : linkTimestamps.entrySet()) {
607 LinkFragmentId linkFragmentId = entry.getKey();
608 Timestamp peerTimestamp = entry.getValue();
609
610 LinkKey key = linkFragmentId.linkKey();
611 ProviderId providerId = linkFragmentId.providerId();
612
613 Timestamped<LinkDescription> linkDescription = getLinkDescription(key, providerId);
614 if (linkDescription.isNewer(peerTimestamp)) {
615 // I have more recent link description. update peer.
616 notifyPeer(peer, new InternalLinkEvent(providerId, linkDescription));
617 }
618 // else TODO: Peer has more recent link description. request it.
619
620 Timestamp linkRemovedTimestamp = removedLinks.get(key);
621 if (linkRemovedTimestamp != null && linkRemovedTimestamp.compareTo(peerTimestamp) > 0) {
622 // peer has a zombie link. update peer.
623 notifyPeer(peer, new InternalLinkRemovedEvent(key, linkRemovedTimestamp));
624 }
625 }
626
627 for (Map.Entry<LinkKey, Timestamp> entry : linkTombstones.entrySet()) {
628 LinkKey key = entry.getKey();
629 Timestamp peerTimestamp = entry.getValue();
630
631 ProviderId primaryProviderId = pickPrimaryProviderId(getLinkDescriptions(key));
632 if (primaryProviderId != null) {
633 if (!getLinkDescription(key, primaryProviderId).isNewer(peerTimestamp)) {
634 notifyDelegateIfNotNull(removeLinkInternal(key, peerTimestamp));
635 }
636 }
637 }
638 }
639
Madan Jampani2ff05592014-10-10 15:42:47 -0700640 private class InternalLinkEventListener implements ClusterMessageHandler {
641 @Override
642 public void handle(ClusterMessage message) {
643
644 log.info("Received link event from peer: {}", message.sender());
645 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
646
647 ProviderId providerId = event.providerId();
648 Timestamped<LinkDescription> linkDescription = event.linkDescription();
649
650 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
651 }
652 }
653
654 private class InternalLinkRemovedEventListener implements ClusterMessageHandler {
655 @Override
656 public void handle(ClusterMessage message) {
657
658 log.info("Received link removed event from peer: {}", message.sender());
659 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
660
661 LinkKey linkKey = event.linkKey();
662 Timestamp timestamp = event.timestamp();
663
664 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
665 }
666 }
Madan Jampania97e8202014-10-10 17:01:33 -0700667
668 private final class InternalLinkAntiEntropyAdvertisementListener implements ClusterMessageHandler {
669
670 @Override
671 public void handle(ClusterMessage message) {
672 log.info("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
673 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
674 handleAntiEntropyAdvertisement(advertisement);
675 }
676 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700677}