blob: 6e8a36717115c0c26a4cded65ad7d9bef7ce76c9 [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;
42import org.onlab.onos.store.common.impl.Timestamped;
43import org.onlab.onos.store.serializers.DistributedStoreSerializers;
44import org.onlab.onos.store.serializers.KryoSerializer;
45import org.onlab.util.KryoPool;
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() {
113 serializerPool = KryoPool.newBuilder()
114 .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();
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
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700380 private static Timestamped<LinkDescription> getPrimaryDescription(
381 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
382
Madan Jampani2ff05592014-10-10 15:42:47 -0700383 synchronized (linkDescriptions) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700384 for (Entry<ProviderId, Timestamped<LinkDescription>>
385 e : linkDescriptions.entrySet()) {
386
387 if (!e.getKey().isAncillary()) {
388 return e.getValue();
389 }
390 }
391 }
392 return null;
393 }
394
395
396 // TODO: consider slicing out as Timestamp utils
397 /**
398 * Checks is timestamp is more recent than timestamped object.
399 *
400 * @param timestamp to check if this is more recent then other
401 * @param timestamped object to be tested against
402 * @return true if {@code timestamp} is more recent than {@code timestamped}
403 * or {@code timestamped is null}
404 */
405 private static boolean isMoreRecent(Timestamp timestamp, Timestamped<?> timestamped) {
406 checkNotNull(timestamp);
407 if (timestamped == null) {
408 return true;
409 }
410 return timestamp.compareTo(timestamped.timestamp()) > 0;
411 }
412
413 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
414 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions
415 = getOrCreateLinkDescriptions(key);
416
417 synchronized (linkDescriptions) {
418 if (linkDescriptions.isEmpty()) {
419 // never seen such link before. keeping timestamp for record
420 removedLinks.put(key, timestamp);
421 return null;
422 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700423 // accept removal request if given timestamp is newer than
424 // the latest Timestamp from Primary provider
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700425 Timestamped<LinkDescription> prim = getPrimaryDescription(linkDescriptions);
426 if (!isMoreRecent(timestamp, prim)) {
427 // outdated remove request, ignore
Madan Jampani2ff05592014-10-10 15:42:47 -0700428 return null;
429 }
430 removedLinks.put(key, timestamp);
431 Link link = links.remove(key);
432 linkDescriptions.clear();
433 if (link != null) {
434 srcLinks.remove(link.src().deviceId(), key);
435 dstLinks.remove(link.dst().deviceId(), key);
436 return new LinkEvent(LINK_REMOVED, link);
437 }
438 return null;
439 }
440 }
441
442 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
443 return synchronizedSetMultimap(HashMultimap.<K, V>create());
444 }
445
446 /**
447 * @return primary ProviderID, or randomly chosen one if none exists
448 */
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700449 private static ProviderId pickBaseProviderId(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700450 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700451
452 ProviderId fallBackPrimary = null;
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700453 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700454 if (!e.getKey().isAncillary()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700455 // found primary
Madan Jampani2ff05592014-10-10 15:42:47 -0700456 return e.getKey();
457 } else if (fallBackPrimary == null) {
458 // pick randomly as a fallback in case there is no primary
459 fallBackPrimary = e.getKey();
460 }
461 }
462 return fallBackPrimary;
463 }
464
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700465 // Guarded by linkDescs value (=locking each Link)
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700466 private Link composeLink(Map<ProviderId, Timestamped<LinkDescription>> descs) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700467 ProviderId baseProviderId = pickBaseProviderId(descs);
468 Timestamped<LinkDescription> base = descs.get(baseProviderId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700469
470 ConnectPoint src = base.value().src();
471 ConnectPoint dst = base.value().dst();
472 Type type = base.value().type();
473 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
474 annotations = merge(annotations, base.value().annotations());
475
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700476 for (Entry<ProviderId, Timestamped<LinkDescription>> e : descs.entrySet()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700477 if (baseProviderId.equals(e.getKey())) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700478 continue;
479 }
480
481 // TODO: should keep track of Description timestamp
482 // and only merge conflicting keys when timestamp is newer
483 // Currently assuming there will never be a key conflict between
484 // providers
485
486 // annotation merging. not so efficient, should revisit later
487 annotations = merge(annotations, e.getValue().value().annotations());
488 }
489
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700490 return new DefaultLink(baseProviderId, src, dst, type, annotations);
Madan Jampani2ff05592014-10-10 15:42:47 -0700491 }
492
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700493 private Map<ProviderId, Timestamped<LinkDescription>> getOrCreateLinkDescriptions(LinkKey key) {
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700494 Map<ProviderId, Timestamped<LinkDescription>> r;
495 r = linkDescs.get(key);
496 if (r != null) {
497 return r;
498 }
499 r = new HashMap<>();
500 final Map<ProviderId, Timestamped<LinkDescription>> concurrentlyAdded;
501 concurrentlyAdded = linkDescs.putIfAbsent(key, r);
502 if (concurrentlyAdded != null) {
503 return concurrentlyAdded;
504 } else {
505 return r;
506 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700507 }
508
509 private final Function<LinkKey, Link> lookupLink = new LookupLink();
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700510 /**
511 * Returns a Function to lookup Link instance using LinkKey from cache.
512 * @return
513 */
Madan Jampani2ff05592014-10-10 15:42:47 -0700514 private Function<LinkKey, Link> lookupLink() {
515 return lookupLink;
516 }
517
518 private final class LookupLink implements Function<LinkKey, Link> {
519 @Override
520 public Link apply(LinkKey input) {
Yuta HIGUCHI023295a2014-10-15 23:29:46 -0700521 if (input == null) {
522 return null;
523 } else {
524 return links.get(input);
525 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700526 }
527 }
528
Madan Jampani2ff05592014-10-10 15:42:47 -0700529 private void notifyDelegateIfNotNull(LinkEvent event) {
530 if (event != null) {
531 notifyDelegate(event);
532 }
533 }
534
Madan Jampani2ff05592014-10-10 15:42:47 -0700535 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
536 ClusterMessage message = new ClusterMessage(
537 clusterService.getLocalNode().id(),
538 subject,
539 SERIALIZER.encode(event));
540 clusterCommunicator.broadcast(message);
541 }
542
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700543 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
544 ClusterMessage message = new ClusterMessage(
545 clusterService.getLocalNode().id(),
546 subject,
547 SERIALIZER.encode(event));
548 clusterCommunicator.unicast(message, recipient);
Madan Jampania97e8202014-10-10 17:01:33 -0700549 }
550
Madan Jampani2ff05592014-10-10 15:42:47 -0700551 private void notifyPeers(InternalLinkEvent event) throws IOException {
552 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
553 }
554
555 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
556 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
557 }
558
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700559 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700560 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700561 try {
562 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
563 } catch (IOException e) {
564 log.debug("Failed to notify peer {} with message {}", peer, event);
565 }
Madan Jampania97e8202014-10-10 17:01:33 -0700566 }
567
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700568 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700569 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700570 try {
571 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
572 } catch (IOException e) {
573 log.debug("Failed to notify peer {} with message {}", peer, event);
574 }
Madan Jampania97e8202014-10-10 17:01:33 -0700575 }
576
577 private final class SendAdvertisementTask implements Runnable {
578
579 @Override
580 public void run() {
581 if (Thread.currentThread().isInterrupted()) {
582 log.info("Interrupted, quitting");
583 return;
584 }
585
586 try {
587 final NodeId self = clusterService.getLocalNode().id();
588 Set<ControllerNode> nodes = clusterService.getNodes();
589
590 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
591 .transform(toNodeId())
592 .toList();
593
594 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -0700595 log.debug("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700596 return;
597 }
598
599 NodeId peer;
600 do {
601 int idx = RandomUtils.nextInt(0, nodeIds.size());
602 peer = nodeIds.get(idx);
603 } while (peer.equals(self));
604
605 LinkAntiEntropyAdvertisement ad = createAdvertisement();
606
607 if (Thread.currentThread().isInterrupted()) {
608 log.info("Interrupted, quitting");
609 return;
610 }
611
612 try {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700613 unicastMessage(peer, LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
614 } catch (IOException e) {
615 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Madan Jampania97e8202014-10-10 17:01:33 -0700616 return;
617 }
618 } catch (Exception e) {
619 // catch all Exception to avoid Scheduled task being suppressed.
620 log.error("Exception thrown while sending advertisement", e);
621 }
622 }
623 }
624
625 private LinkAntiEntropyAdvertisement createAdvertisement() {
626 final NodeId self = clusterService.getLocalNode().id();
627
628 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
629 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
630
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700631 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
Madan Jampania97e8202014-10-10 17:01:33 -0700632 provs : linkDescs.entrySet()) {
633
634 final LinkKey linkKey = provs.getKey();
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700635 final Map<ProviderId, Timestamped<LinkDescription>> linkDesc = provs.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700636 synchronized (linkDesc) {
637 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
638 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
639 }
640 }
641 }
642
643 linkTombstones.putAll(removedLinks);
644
645 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
646 }
647
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700648 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement ad) {
Madan Jampania97e8202014-10-10 17:01:33 -0700649
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700650 final NodeId sender = ad.sender();
651 boolean localOutdated = false;
Madan Jampania97e8202014-10-10 17:01:33 -0700652
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700653 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
654 l : linkDescs.entrySet()) {
Madan Jampania97e8202014-10-10 17:01:33 -0700655
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700656 final LinkKey key = l.getKey();
657 final Map<ProviderId, Timestamped<LinkDescription>> link = l.getValue();
658 synchronized (link) {
659 Timestamp localLatest = removedLinks.get(key);
Madan Jampania97e8202014-10-10 17:01:33 -0700660
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700661 for (Entry<ProviderId, Timestamped<LinkDescription>> p : link.entrySet()) {
662 final ProviderId providerId = p.getKey();
663 final Timestamped<LinkDescription> pDesc = p.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700664
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700665 final LinkFragmentId fragId = new LinkFragmentId(key, providerId);
666 // remote
667 Timestamp remoteTimestamp = ad.linkTimestamps().get(fragId);
668 if (remoteTimestamp == null) {
669 remoteTimestamp = ad.linkTombstones().get(key);
670 }
671 if (remoteTimestamp == null ||
672 pDesc.isNewer(remoteTimestamp)) {
673 // I have more recent link description. update peer.
674 notifyPeer(sender, new InternalLinkEvent(providerId, pDesc));
675 } else {
676 final Timestamp remoteLive = ad.linkTimestamps().get(fragId);
677 if (remoteLive != null &&
678 remoteLive.compareTo(pDesc.timestamp()) > 0) {
679 // I have something outdated
680 localOutdated = true;
681 }
682 }
683
684 // search local latest along the way
685 if (localLatest == null ||
686 pDesc.isNewer(localLatest)) {
687 localLatest = pDesc.timestamp();
688 }
689 }
690 // Tests if remote remove is more recent then local latest.
691 final Timestamp remoteRemove = ad.linkTombstones().get(key);
692 if (remoteRemove != null) {
693 if (localLatest != null &&
694 localLatest.compareTo(remoteRemove) < 0) {
695 // remote remove is more recent
696 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
697 }
698 }
Madan Jampania97e8202014-10-10 17:01:33 -0700699 }
700 }
701
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700702 // populate remove info if not known locally
703 for (Entry<LinkKey, Timestamp> remoteRm : ad.linkTombstones().entrySet()) {
704 final LinkKey key = remoteRm.getKey();
705 final Timestamp remoteRemove = remoteRm.getValue();
706 // relying on removeLinkInternal to ignore stale info
707 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
708 }
Madan Jampania97e8202014-10-10 17:01:33 -0700709
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700710 if (localOutdated) {
711 // send back advertisement to speed up convergence
712 try {
713 unicastMessage(sender, LINK_ANTI_ENTROPY_ADVERTISEMENT,
714 createAdvertisement());
715 } catch (IOException e) {
716 log.debug("Failed to send back active advertisement");
Madan Jampania97e8202014-10-10 17:01:33 -0700717 }
718 }
719 }
720
Madan Jampani2ff05592014-10-10 15:42:47 -0700721 private class InternalLinkEventListener implements ClusterMessageHandler {
722 @Override
723 public void handle(ClusterMessage message) {
724
725 log.info("Received link event from peer: {}", message.sender());
726 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
727
728 ProviderId providerId = event.providerId();
729 Timestamped<LinkDescription> linkDescription = event.linkDescription();
730
731 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
732 }
733 }
734
735 private class InternalLinkRemovedEventListener implements ClusterMessageHandler {
736 @Override
737 public void handle(ClusterMessage message) {
738
739 log.info("Received link removed event from peer: {}", message.sender());
740 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
741
742 LinkKey linkKey = event.linkKey();
743 Timestamp timestamp = event.timestamp();
744
745 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
746 }
747 }
Madan Jampania97e8202014-10-10 17:01:33 -0700748
749 private final class InternalLinkAntiEntropyAdvertisementListener implements ClusterMessageHandler {
750
751 @Override
752 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -0700753 log.debug("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
Madan Jampania97e8202014-10-10 17:01:33 -0700754 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
755 handleAntiEntropyAdvertisement(advertisement);
756 }
757 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700758}