blob: 312d072c9a0a4bc41e7c69ea03ff0dd455492ed1 [file] [log] [blame]
Madan Jampani2ff05592014-10-10 15:42:47 -07001package org.onlab.onos.store.link.impl;
2
3import com.google.common.base.Function;
Madan Jampani2ff05592014-10-10 15:42:47 -07004import com.google.common.collect.FluentIterable;
5import com.google.common.collect.HashMultimap;
Madan Jampania97e8202014-10-10 17:01:33 -07006import com.google.common.collect.ImmutableList;
Madan Jampani2ff05592014-10-10 15:42:47 -07007import com.google.common.collect.Maps;
8import com.google.common.collect.SetMultimap;
9
Madan Jampania97e8202014-10-10 17:01:33 -070010import org.apache.commons.lang3.RandomUtils;
Madan Jampani2ff05592014-10-10 15:42:47 -070011import org.apache.felix.scr.annotations.Activate;
12import org.apache.felix.scr.annotations.Component;
13import org.apache.felix.scr.annotations.Deactivate;
14import org.apache.felix.scr.annotations.Reference;
15import org.apache.felix.scr.annotations.ReferenceCardinality;
16import org.apache.felix.scr.annotations.Service;
17import org.onlab.onos.cluster.ClusterService;
Madan Jampania97e8202014-10-10 17:01:33 -070018import org.onlab.onos.cluster.ControllerNode;
19import org.onlab.onos.cluster.NodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070020import org.onlab.onos.net.AnnotationsUtil;
21import org.onlab.onos.net.ConnectPoint;
22import org.onlab.onos.net.DefaultAnnotations;
23import org.onlab.onos.net.DefaultLink;
24import org.onlab.onos.net.DeviceId;
25import org.onlab.onos.net.Link;
26import org.onlab.onos.net.SparseAnnotations;
27import org.onlab.onos.net.Link.Type;
28import org.onlab.onos.net.LinkKey;
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -070029import org.onlab.onos.net.device.DeviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -070030import org.onlab.onos.net.link.DefaultLinkDescription;
31import org.onlab.onos.net.link.LinkDescription;
32import org.onlab.onos.net.link.LinkEvent;
33import org.onlab.onos.net.link.LinkStore;
34import org.onlab.onos.net.link.LinkStoreDelegate;
35import org.onlab.onos.net.provider.ProviderId;
36import org.onlab.onos.store.AbstractStore;
Madan Jampani2ff05592014-10-10 15:42:47 -070037import org.onlab.onos.store.Timestamp;
38import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
39import org.onlab.onos.store.cluster.messaging.ClusterMessage;
40import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
41import org.onlab.onos.store.cluster.messaging.MessageSubject;
Yuta HIGUCHIeecee552014-10-16 14:09:01 -070042import org.onlab.onos.store.impl.Timestamped;
Madan Jampani2ff05592014-10-10 15:42:47 -070043import org.onlab.onos.store.serializers.DistributedStoreSerializers;
44import org.onlab.onos.store.serializers.KryoSerializer;
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070045import org.onlab.util.KryoNamespace;
Madan Jampani2ff05592014-10-10 15:42:47 -070046import org.slf4j.Logger;
47
48import java.io.IOException;
49import java.util.Collections;
Madan Jampania97e8202014-10-10 17:01:33 -070050import java.util.HashMap;
Madan Jampani2ff05592014-10-10 15:42:47 -070051import java.util.HashSet;
52import java.util.Map;
53import java.util.Set;
54import java.util.Map.Entry;
55import java.util.concurrent.ConcurrentHashMap;
56import java.util.concurrent.ConcurrentMap;
Madan Jampania97e8202014-10-10 17:01:33 -070057import java.util.concurrent.ScheduledExecutorService;
58import java.util.concurrent.TimeUnit;
Madan Jampani2ff05592014-10-10 15:42:47 -070059
Madan Jampania97e8202014-10-10 17:01:33 -070060import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
61import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070062import static org.onlab.onos.net.DefaultAnnotations.union;
63import static org.onlab.onos.net.DefaultAnnotations.merge;
64import static org.onlab.onos.net.Link.Type.DIRECT;
65import static org.onlab.onos.net.Link.Type.INDIRECT;
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -070066import static org.onlab.onos.net.LinkKey.linkKey;
Madan Jampani2ff05592014-10-10 15:42:47 -070067import static org.onlab.onos.net.link.LinkEvent.Type.*;
Madan Jampania97e8202014-10-10 17:01:33 -070068import static org.onlab.util.Tools.namedThreads;
Madan Jampani2ff05592014-10-10 15:42:47 -070069import static org.slf4j.LoggerFactory.getLogger;
70import static com.google.common.collect.Multimaps.synchronizedSetMultimap;
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -070071import static com.google.common.base.Preconditions.checkNotNull;
Madan Jampani2ff05592014-10-10 15:42:47 -070072import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -070073import static org.onlab.onos.store.link.impl.GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT;
Madan Jampani2ff05592014-10-10 15:42:47 -070074
75/**
76 * Manages inventory of infrastructure links in distributed data store
77 * that uses optimistic replication and gossip based techniques.
78 */
79@Component(immediate = true)
80@Service
81public class GossipLinkStore
82 extends AbstractStore<LinkEvent, LinkStoreDelegate>
83 implements LinkStore {
84
85 private final Logger log = getLogger(getClass());
86
87 // Link inventory
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -070088 private final ConcurrentMap<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>> linkDescs =
Madan Jampani2ff05592014-10-10 15:42:47 -070089 new ConcurrentHashMap<>();
90
91 // Link instance cache
92 private final ConcurrentMap<LinkKey, Link> links = new ConcurrentHashMap<>();
93
94 // Egress and ingress link sets
95 private final SetMultimap<DeviceId, LinkKey> srcLinks = createSynchronizedHashMultiMap();
96 private final SetMultimap<DeviceId, LinkKey> dstLinks = createSynchronizedHashMultiMap();
97
98 // Remove links
99 private final Map<LinkKey, Timestamp> removedLinks = Maps.newHashMap();
100
101 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700102 protected DeviceClockService deviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -0700103
104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
105 protected ClusterCommunicationService clusterCommunicator;
106
107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
108 protected ClusterService clusterService;
109
110 private static final KryoSerializer SERIALIZER = new KryoSerializer() {
111 @Override
112 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700113 serializerPool = KryoNamespace.newBuilder()
Madan Jampani2ff05592014-10-10 15:42:47 -0700114 .register(DistributedStoreSerializers.COMMON)
115 .register(InternalLinkEvent.class)
116 .register(InternalLinkRemovedEvent.class)
Madan Jampanid2054d42014-10-10 17:27:06 -0700117 .register(LinkAntiEntropyAdvertisement.class)
118 .register(LinkFragmentId.class)
Madan Jampani2ff05592014-10-10 15:42:47 -0700119 .build()
120 .populate(1);
121 }
122 };
123
Madan Jampania97e8202014-10-10 17:01:33 -0700124 private ScheduledExecutorService executor;
125
Madan Jampani2ff05592014-10-10 15:42:47 -0700126 @Activate
127 public void activate() {
128
129 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700130 GossipLinkStoreMessageSubjects.LINK_UPDATE,
131 new InternalLinkEventListener());
Madan Jampani2ff05592014-10-10 15:42:47 -0700132 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700133 GossipLinkStoreMessageSubjects.LINK_REMOVED,
134 new InternalLinkRemovedEventListener());
135 clusterCommunicator.addSubscriber(
136 GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT,
137 new InternalLinkAntiEntropyAdvertisementListener());
138
139 executor =
140 newSingleThreadScheduledExecutor(namedThreads("link-anti-entropy-%d"));
141
142 // TODO: Make these configurable
143 long initialDelaySec = 5;
144 long periodSec = 5;
145 // start anti-entropy thread
146 executor.scheduleAtFixedRate(new SendAdvertisementTask(),
147 initialDelaySec, periodSec, TimeUnit.SECONDS);
Madan Jampani2ff05592014-10-10 15:42:47 -0700148
149 log.info("Started");
150 }
151
152 @Deactivate
153 public void deactivate() {
Madan Jampani3ffbb272014-10-13 11:19:37 -0700154
155 executor.shutdownNow();
156 try {
157 if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
158 log.error("Timeout during executor shutdown");
159 }
160 } catch (InterruptedException e) {
161 log.error("Error during executor shutdown", e);
162 }
163
Madan Jampani2ff05592014-10-10 15:42:47 -0700164 linkDescs.clear();
165 links.clear();
166 srcLinks.clear();
167 dstLinks.clear();
168 log.info("Stopped");
169 }
170
171 @Override
172 public int getLinkCount() {
173 return links.size();
174 }
175
176 @Override
177 public Iterable<Link> getLinks() {
178 return Collections.unmodifiableCollection(links.values());
179 }
180
181 @Override
182 public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
183 // lock for iteration
184 synchronized (srcLinks) {
185 return FluentIterable.from(srcLinks.get(deviceId))
186 .transform(lookupLink())
187 .filter(notNull())
188 .toSet();
189 }
190 }
191
192 @Override
193 public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
194 // lock for iteration
195 synchronized (dstLinks) {
196 return FluentIterable.from(dstLinks.get(deviceId))
197 .transform(lookupLink())
198 .filter(notNull())
199 .toSet();
200 }
201 }
202
203 @Override
204 public Link getLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700205 return links.get(linkKey(src, dst));
Madan Jampani2ff05592014-10-10 15:42:47 -0700206 }
207
208 @Override
209 public Set<Link> getEgressLinks(ConnectPoint src) {
210 Set<Link> egress = new HashSet<>();
211 for (LinkKey linkKey : srcLinks.get(src.deviceId())) {
212 if (linkKey.src().equals(src)) {
213 egress.add(links.get(linkKey));
214 }
215 }
216 return egress;
217 }
218
219 @Override
220 public Set<Link> getIngressLinks(ConnectPoint dst) {
221 Set<Link> ingress = new HashSet<>();
222 for (LinkKey linkKey : dstLinks.get(dst.deviceId())) {
223 if (linkKey.dst().equals(dst)) {
224 ingress.add(links.get(linkKey));
225 }
226 }
227 return ingress;
228 }
229
230 @Override
231 public LinkEvent createOrUpdateLink(ProviderId providerId,
232 LinkDescription linkDescription) {
233
234 DeviceId dstDeviceId = linkDescription.dst().deviceId();
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700235 Timestamp newTimestamp = deviceClockService.getTimestamp(dstDeviceId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700236
237 final Timestamped<LinkDescription> deltaDesc = new Timestamped<>(linkDescription, newTimestamp);
238
Yuta HIGUCHI990aecc2014-10-13 22:21:42 -0700239 LinkKey key = linkKey(linkDescription.src(), linkDescription.dst());
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700240 final LinkEvent event;
241 final Timestamped<LinkDescription> mergedDesc;
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700242 synchronized (getOrCreateLinkDescriptions(key)) {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700243 event = createOrUpdateLinkInternal(providerId, deltaDesc);
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700244 mergedDesc = getOrCreateLinkDescriptions(key).get(providerId);
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700245 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700246
247 if (event != null) {
248 log.info("Notifying peers of a link update topology event from providerId: "
249 + "{} between src: {} and dst: {}",
250 providerId, linkDescription.src(), linkDescription.dst());
251 try {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700252 notifyPeers(new InternalLinkEvent(providerId, mergedDesc));
Madan Jampani2ff05592014-10-10 15:42:47 -0700253 } catch (IOException e) {
254 log.info("Failed to notify peers of a link update topology event from providerId: "
255 + "{} between src: {} and dst: {}",
256 providerId, linkDescription.src(), linkDescription.dst());
257 }
258 }
259 return event;
260 }
261
262 private LinkEvent createOrUpdateLinkInternal(
263 ProviderId providerId,
264 Timestamped<LinkDescription> linkDescription) {
265
Yuta HIGUCHI990aecc2014-10-13 22:21:42 -0700266 LinkKey key = linkKey(linkDescription.value().src(),
267 linkDescription.value().dst());
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700268 Map<ProviderId, Timestamped<LinkDescription>> descs = getOrCreateLinkDescriptions(key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700269
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(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700295 Map<ProviderId, Timestamped<LinkDescription>> descs,
Madan Jampani2ff05592014-10-10 15:42:47 -0700296 ProviderId providerId,
297 Timestamped<LinkDescription> linkDescription) {
298
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700299 // merge existing annotations
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700300 Timestamped<LinkDescription> existingLinkDescription = descs.get(providerId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700301 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 }
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700315 return descs.put(providerId, newLinkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700316 }
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) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700360 final LinkKey key = linkKey(src, dst);
Madan Jampani2ff05592014-10-10 15:42:47 -0700361
362 DeviceId dstDeviceId = dst.deviceId();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700363 Timestamp timestamp = null;
364 try {
365 timestamp = deviceClockService.getTimestamp(dstDeviceId);
366 } catch (IllegalStateException e) {
367 //there are times when this is called before mastership
368 // handoff correctly completes.
369 return null;
370 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700371
372 LinkEvent event = removeLinkInternal(key, timestamp);
373
374 if (event != null) {
375 log.info("Notifying peers of a link removed topology event for a link "
376 + "between src: {} and dst: {}", src, dst);
377 try {
378 notifyPeers(new InternalLinkRemovedEvent(key, timestamp));
379 } catch (IOException e) {
380 log.error("Failed to notify peers of a link removed topology event for a link "
381 + "between src: {} and dst: {}", src, dst);
382 }
383 }
384 return event;
385 }
386
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700387 private static Timestamped<LinkDescription> getPrimaryDescription(
388 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
389
Madan Jampani2ff05592014-10-10 15:42:47 -0700390 synchronized (linkDescriptions) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700391 for (Entry<ProviderId, Timestamped<LinkDescription>>
392 e : linkDescriptions.entrySet()) {
393
394 if (!e.getKey().isAncillary()) {
395 return e.getValue();
396 }
397 }
398 }
399 return null;
400 }
401
402
403 // TODO: consider slicing out as Timestamp utils
404 /**
405 * Checks is timestamp is more recent than timestamped object.
406 *
407 * @param timestamp to check if this is more recent then other
408 * @param timestamped object to be tested against
409 * @return true if {@code timestamp} is more recent than {@code timestamped}
410 * or {@code timestamped is null}
411 */
412 private static boolean isMoreRecent(Timestamp timestamp, Timestamped<?> timestamped) {
413 checkNotNull(timestamp);
414 if (timestamped == null) {
415 return true;
416 }
417 return timestamp.compareTo(timestamped.timestamp()) > 0;
418 }
419
420 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
421 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions
422 = getOrCreateLinkDescriptions(key);
423
424 synchronized (linkDescriptions) {
425 if (linkDescriptions.isEmpty()) {
426 // never seen such link before. keeping timestamp for record
427 removedLinks.put(key, timestamp);
428 return null;
429 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700430 // accept removal request if given timestamp is newer than
431 // the latest Timestamp from Primary provider
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700432 Timestamped<LinkDescription> prim = getPrimaryDescription(linkDescriptions);
433 if (!isMoreRecent(timestamp, prim)) {
434 // outdated remove request, ignore
Madan Jampani2ff05592014-10-10 15:42:47 -0700435 return null;
436 }
437 removedLinks.put(key, timestamp);
438 Link link = links.remove(key);
439 linkDescriptions.clear();
440 if (link != null) {
441 srcLinks.remove(link.src().deviceId(), key);
442 dstLinks.remove(link.dst().deviceId(), key);
443 return new LinkEvent(LINK_REMOVED, link);
444 }
445 return null;
446 }
447 }
448
449 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
450 return synchronizedSetMultimap(HashMultimap.<K, V>create());
451 }
452
453 /**
454 * @return primary ProviderID, or randomly chosen one if none exists
455 */
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700456 private static ProviderId pickBaseProviderId(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700457 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700458
459 ProviderId fallBackPrimary = null;
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700460 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700461 if (!e.getKey().isAncillary()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700462 // found primary
Madan Jampani2ff05592014-10-10 15:42:47 -0700463 return e.getKey();
464 } else if (fallBackPrimary == null) {
465 // pick randomly as a fallback in case there is no primary
466 fallBackPrimary = e.getKey();
467 }
468 }
469 return fallBackPrimary;
470 }
471
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700472 // Guarded by linkDescs value (=locking each Link)
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700473 private Link composeLink(Map<ProviderId, Timestamped<LinkDescription>> descs) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700474 ProviderId baseProviderId = pickBaseProviderId(descs);
475 Timestamped<LinkDescription> base = descs.get(baseProviderId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700476
477 ConnectPoint src = base.value().src();
478 ConnectPoint dst = base.value().dst();
479 Type type = base.value().type();
480 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
481 annotations = merge(annotations, base.value().annotations());
482
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700483 for (Entry<ProviderId, Timestamped<LinkDescription>> e : descs.entrySet()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700484 if (baseProviderId.equals(e.getKey())) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700485 continue;
486 }
487
488 // TODO: should keep track of Description timestamp
489 // and only merge conflicting keys when timestamp is newer
490 // Currently assuming there will never be a key conflict between
491 // providers
492
493 // annotation merging. not so efficient, should revisit later
494 annotations = merge(annotations, e.getValue().value().annotations());
495 }
496
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700497 return new DefaultLink(baseProviderId, src, dst, type, annotations);
Madan Jampani2ff05592014-10-10 15:42:47 -0700498 }
499
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700500 private Map<ProviderId, Timestamped<LinkDescription>> getOrCreateLinkDescriptions(LinkKey key) {
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700501 Map<ProviderId, Timestamped<LinkDescription>> r;
502 r = linkDescs.get(key);
503 if (r != null) {
504 return r;
505 }
506 r = new HashMap<>();
507 final Map<ProviderId, Timestamped<LinkDescription>> concurrentlyAdded;
508 concurrentlyAdded = linkDescs.putIfAbsent(key, r);
509 if (concurrentlyAdded != null) {
510 return concurrentlyAdded;
511 } else {
512 return r;
513 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700514 }
515
516 private final Function<LinkKey, Link> lookupLink = new LookupLink();
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700517 /**
518 * Returns a Function to lookup Link instance using LinkKey from cache.
519 * @return
520 */
Madan Jampani2ff05592014-10-10 15:42:47 -0700521 private Function<LinkKey, Link> lookupLink() {
522 return lookupLink;
523 }
524
525 private final class LookupLink implements Function<LinkKey, Link> {
526 @Override
527 public Link apply(LinkKey input) {
Yuta HIGUCHI023295a2014-10-15 23:29:46 -0700528 if (input == null) {
529 return null;
530 } else {
531 return links.get(input);
532 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700533 }
534 }
535
Madan Jampani2ff05592014-10-10 15:42:47 -0700536 private void notifyDelegateIfNotNull(LinkEvent event) {
537 if (event != null) {
538 notifyDelegate(event);
539 }
540 }
541
Madan Jampani2ff05592014-10-10 15:42:47 -0700542 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
543 ClusterMessage message = new ClusterMessage(
544 clusterService.getLocalNode().id(),
545 subject,
546 SERIALIZER.encode(event));
547 clusterCommunicator.broadcast(message);
548 }
549
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700550 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
551 ClusterMessage message = new ClusterMessage(
552 clusterService.getLocalNode().id(),
553 subject,
554 SERIALIZER.encode(event));
555 clusterCommunicator.unicast(message, recipient);
Madan Jampania97e8202014-10-10 17:01:33 -0700556 }
557
Madan Jampani2ff05592014-10-10 15:42:47 -0700558 private void notifyPeers(InternalLinkEvent event) throws IOException {
559 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
560 }
561
562 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
563 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
564 }
565
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700566 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700567 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700568 try {
569 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
570 } catch (IOException e) {
571 log.debug("Failed to notify peer {} with message {}", peer, event);
572 }
Madan Jampania97e8202014-10-10 17:01:33 -0700573 }
574
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700575 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700576 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700577 try {
578 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
579 } catch (IOException e) {
580 log.debug("Failed to notify peer {} with message {}", peer, event);
581 }
Madan Jampania97e8202014-10-10 17:01:33 -0700582 }
583
584 private final class SendAdvertisementTask implements Runnable {
585
586 @Override
587 public void run() {
588 if (Thread.currentThread().isInterrupted()) {
589 log.info("Interrupted, quitting");
590 return;
591 }
592
593 try {
594 final NodeId self = clusterService.getLocalNode().id();
595 Set<ControllerNode> nodes = clusterService.getNodes();
596
597 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
598 .transform(toNodeId())
599 .toList();
600
601 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -0700602 log.debug("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700603 return;
604 }
605
606 NodeId peer;
607 do {
608 int idx = RandomUtils.nextInt(0, nodeIds.size());
609 peer = nodeIds.get(idx);
610 } while (peer.equals(self));
611
612 LinkAntiEntropyAdvertisement ad = createAdvertisement();
613
614 if (Thread.currentThread().isInterrupted()) {
615 log.info("Interrupted, quitting");
616 return;
617 }
618
619 try {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700620 unicastMessage(peer, LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
621 } catch (IOException e) {
622 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Madan Jampania97e8202014-10-10 17:01:33 -0700623 return;
624 }
625 } catch (Exception e) {
626 // catch all Exception to avoid Scheduled task being suppressed.
627 log.error("Exception thrown while sending advertisement", e);
628 }
629 }
630 }
631
632 private LinkAntiEntropyAdvertisement createAdvertisement() {
633 final NodeId self = clusterService.getLocalNode().id();
634
635 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
636 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
637
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700638 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
Madan Jampania97e8202014-10-10 17:01:33 -0700639 provs : linkDescs.entrySet()) {
640
641 final LinkKey linkKey = provs.getKey();
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700642 final Map<ProviderId, Timestamped<LinkDescription>> linkDesc = provs.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700643 synchronized (linkDesc) {
644 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
645 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
646 }
647 }
648 }
649
650 linkTombstones.putAll(removedLinks);
651
652 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
653 }
654
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700655 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement ad) {
Madan Jampania97e8202014-10-10 17:01:33 -0700656
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700657 final NodeId sender = ad.sender();
658 boolean localOutdated = false;
Madan Jampania97e8202014-10-10 17:01:33 -0700659
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700660 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
661 l : linkDescs.entrySet()) {
Madan Jampania97e8202014-10-10 17:01:33 -0700662
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700663 final LinkKey key = l.getKey();
664 final Map<ProviderId, Timestamped<LinkDescription>> link = l.getValue();
665 synchronized (link) {
666 Timestamp localLatest = removedLinks.get(key);
Madan Jampania97e8202014-10-10 17:01:33 -0700667
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700668 for (Entry<ProviderId, Timestamped<LinkDescription>> p : link.entrySet()) {
669 final ProviderId providerId = p.getKey();
670 final Timestamped<LinkDescription> pDesc = p.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700671
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700672 final LinkFragmentId fragId = new LinkFragmentId(key, providerId);
673 // remote
674 Timestamp remoteTimestamp = ad.linkTimestamps().get(fragId);
675 if (remoteTimestamp == null) {
676 remoteTimestamp = ad.linkTombstones().get(key);
677 }
678 if (remoteTimestamp == null ||
679 pDesc.isNewer(remoteTimestamp)) {
680 // I have more recent link description. update peer.
681 notifyPeer(sender, new InternalLinkEvent(providerId, pDesc));
682 } else {
683 final Timestamp remoteLive = ad.linkTimestamps().get(fragId);
684 if (remoteLive != null &&
685 remoteLive.compareTo(pDesc.timestamp()) > 0) {
686 // I have something outdated
687 localOutdated = true;
688 }
689 }
690
691 // search local latest along the way
692 if (localLatest == null ||
693 pDesc.isNewer(localLatest)) {
694 localLatest = pDesc.timestamp();
695 }
696 }
697 // Tests if remote remove is more recent then local latest.
698 final Timestamp remoteRemove = ad.linkTombstones().get(key);
699 if (remoteRemove != null) {
700 if (localLatest != null &&
701 localLatest.compareTo(remoteRemove) < 0) {
702 // remote remove is more recent
703 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
704 }
705 }
Madan Jampania97e8202014-10-10 17:01:33 -0700706 }
707 }
708
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700709 // populate remove info if not known locally
710 for (Entry<LinkKey, Timestamp> remoteRm : ad.linkTombstones().entrySet()) {
711 final LinkKey key = remoteRm.getKey();
712 final Timestamp remoteRemove = remoteRm.getValue();
713 // relying on removeLinkInternal to ignore stale info
714 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
715 }
Madan Jampania97e8202014-10-10 17:01:33 -0700716
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700717 if (localOutdated) {
718 // send back advertisement to speed up convergence
719 try {
720 unicastMessage(sender, LINK_ANTI_ENTROPY_ADVERTISEMENT,
721 createAdvertisement());
722 } catch (IOException e) {
723 log.debug("Failed to send back active advertisement");
Madan Jampania97e8202014-10-10 17:01:33 -0700724 }
725 }
726 }
727
Madan Jampani2ff05592014-10-10 15:42:47 -0700728 private class InternalLinkEventListener implements ClusterMessageHandler {
729 @Override
730 public void handle(ClusterMessage message) {
731
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700732 log.trace("Received link event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700733 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
734
735 ProviderId providerId = event.providerId();
736 Timestamped<LinkDescription> linkDescription = event.linkDescription();
737
738 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
739 }
740 }
741
742 private class InternalLinkRemovedEventListener implements ClusterMessageHandler {
743 @Override
744 public void handle(ClusterMessage message) {
745
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700746 log.trace("Received link removed event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700747 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
748
749 LinkKey linkKey = event.linkKey();
750 Timestamp timestamp = event.timestamp();
751
752 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
753 }
754 }
Madan Jampania97e8202014-10-10 17:01:33 -0700755
756 private final class InternalLinkAntiEntropyAdvertisementListener implements ClusterMessageHandler {
757
758 @Override
759 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -0700760 log.debug("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
Madan Jampania97e8202014-10-10 17:01:33 -0700761 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
762 handleAntiEntropyAdvertisement(advertisement);
763 }
764 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700765}