blob: 9e589046bc0917dfd56bea86d4ac407ce2cb0852 [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;
alshabibdfc7afb2014-10-21 20:13:27 -0700242 Map<ProviderId, Timestamped<LinkDescription>> map = getOrCreateLinkDescriptions(key);
243 synchronized (map) {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700244 event = createOrUpdateLinkInternal(providerId, deltaDesc);
alshabibdfc7afb2014-10-21 20:13:27 -0700245 mergedDesc = map.get(providerId);
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700246 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700247
alshabibdfc7afb2014-10-21 20:13:27 -0700248
249
Madan Jampani2ff05592014-10-10 15:42:47 -0700250 if (event != null) {
251 log.info("Notifying peers of a link update topology event from providerId: "
252 + "{} between src: {} and dst: {}",
253 providerId, linkDescription.src(), linkDescription.dst());
254 try {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700255 notifyPeers(new InternalLinkEvent(providerId, mergedDesc));
Madan Jampani2ff05592014-10-10 15:42:47 -0700256 } catch (IOException e) {
257 log.info("Failed to notify peers of a link update topology event from providerId: "
alshabibdfc7afb2014-10-21 20:13:27 -0700258 + "{} between src: {} and dst: {}",
259 providerId, linkDescription.src(), linkDescription.dst());
Madan Jampani2ff05592014-10-10 15:42:47 -0700260 }
261 }
262 return event;
263 }
264
265 private LinkEvent createOrUpdateLinkInternal(
266 ProviderId providerId,
267 Timestamped<LinkDescription> linkDescription) {
268
Yuta HIGUCHI990aecc2014-10-13 22:21:42 -0700269 LinkKey key = linkKey(linkDescription.value().src(),
270 linkDescription.value().dst());
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700271 Map<ProviderId, Timestamped<LinkDescription>> descs = getOrCreateLinkDescriptions(key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700272
273 synchronized (descs) {
274 // if the link was previously removed, we should proceed if and
275 // only if this request is more recent.
276 Timestamp linkRemovedTimestamp = removedLinks.get(key);
277 if (linkRemovedTimestamp != null) {
278 if (linkDescription.isNewer(linkRemovedTimestamp)) {
279 removedLinks.remove(key);
280 } else {
281 return null;
282 }
283 }
284
285 final Link oldLink = links.get(key);
286 // update description
287 createOrUpdateLinkDescription(descs, providerId, linkDescription);
288 final Link newLink = composeLink(descs);
289 if (oldLink == null) {
290 return createLink(key, newLink);
291 }
292 return updateLink(key, oldLink, newLink);
293 }
294 }
295
296 // Guarded by linkDescs value (=locking each Link)
297 private Timestamped<LinkDescription> createOrUpdateLinkDescription(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700298 Map<ProviderId, Timestamped<LinkDescription>> descs,
Madan Jampani2ff05592014-10-10 15:42:47 -0700299 ProviderId providerId,
300 Timestamped<LinkDescription> linkDescription) {
301
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700302 // merge existing annotations
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700303 Timestamped<LinkDescription> existingLinkDescription = descs.get(providerId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700304 if (existingLinkDescription != null && existingLinkDescription.isNewer(linkDescription)) {
305 return null;
306 }
307 Timestamped<LinkDescription> newLinkDescription = linkDescription;
308 if (existingLinkDescription != null) {
309 SparseAnnotations merged = union(existingLinkDescription.value().annotations(),
310 linkDescription.value().annotations());
311 newLinkDescription = new Timestamped<LinkDescription>(
312 new DefaultLinkDescription(
313 linkDescription.value().src(),
314 linkDescription.value().dst(),
315 linkDescription.value().type(), merged),
316 linkDescription.timestamp());
317 }
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700318 return descs.put(providerId, newLinkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700319 }
320
321 // Creates and stores the link and returns the appropriate event.
322 // Guarded by linkDescs value (=locking each Link)
323 private LinkEvent createLink(LinkKey key, Link newLink) {
324
325 if (newLink.providerId().isAncillary()) {
326 // TODO: revisit ancillary only Link handling
327
328 // currently treating ancillary only as down (not visible outside)
329 return null;
330 }
331
332 links.put(key, newLink);
333 srcLinks.put(newLink.src().deviceId(), key);
334 dstLinks.put(newLink.dst().deviceId(), key);
335 return new LinkEvent(LINK_ADDED, newLink);
336 }
337
338 // Updates, if necessary the specified link and returns the appropriate event.
339 // Guarded by linkDescs value (=locking each Link)
340 private LinkEvent updateLink(LinkKey key, Link oldLink, Link newLink) {
341
342 if (newLink.providerId().isAncillary()) {
343 // TODO: revisit ancillary only Link handling
344
345 // currently treating ancillary only as down (not visible outside)
346 return null;
347 }
348
349 if ((oldLink.type() == INDIRECT && newLink.type() == DIRECT) ||
350 !AnnotationsUtil.isEqual(oldLink.annotations(), newLink.annotations())) {
351
352 links.put(key, newLink);
353 // strictly speaking following can be ommitted
354 srcLinks.put(oldLink.src().deviceId(), key);
355 dstLinks.put(oldLink.dst().deviceId(), key);
356 return new LinkEvent(LINK_UPDATED, newLink);
357 }
358 return null;
359 }
360
361 @Override
362 public LinkEvent removeLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700363 final LinkKey key = linkKey(src, dst);
Madan Jampani2ff05592014-10-10 15:42:47 -0700364
365 DeviceId dstDeviceId = dst.deviceId();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700366 Timestamp timestamp = null;
367 try {
368 timestamp = deviceClockService.getTimestamp(dstDeviceId);
369 } catch (IllegalStateException e) {
370 //there are times when this is called before mastership
371 // handoff correctly completes.
372 return null;
373 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700374
375 LinkEvent event = removeLinkInternal(key, timestamp);
376
377 if (event != null) {
378 log.info("Notifying peers of a link removed topology event for a link "
379 + "between src: {} and dst: {}", src, dst);
380 try {
381 notifyPeers(new InternalLinkRemovedEvent(key, timestamp));
382 } catch (IOException e) {
383 log.error("Failed to notify peers of a link removed topology event for a link "
384 + "between src: {} and dst: {}", src, dst);
385 }
386 }
387 return event;
388 }
389
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700390 private static Timestamped<LinkDescription> getPrimaryDescription(
391 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
392
Madan Jampani2ff05592014-10-10 15:42:47 -0700393 synchronized (linkDescriptions) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700394 for (Entry<ProviderId, Timestamped<LinkDescription>>
395 e : linkDescriptions.entrySet()) {
396
397 if (!e.getKey().isAncillary()) {
398 return e.getValue();
399 }
400 }
401 }
402 return null;
403 }
404
405
406 // TODO: consider slicing out as Timestamp utils
407 /**
408 * Checks is timestamp is more recent than timestamped object.
409 *
410 * @param timestamp to check if this is more recent then other
411 * @param timestamped object to be tested against
412 * @return true if {@code timestamp} is more recent than {@code timestamped}
413 * or {@code timestamped is null}
414 */
415 private static boolean isMoreRecent(Timestamp timestamp, Timestamped<?> timestamped) {
416 checkNotNull(timestamp);
417 if (timestamped == null) {
418 return true;
419 }
420 return timestamp.compareTo(timestamped.timestamp()) > 0;
421 }
422
423 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
424 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions
425 = getOrCreateLinkDescriptions(key);
426
427 synchronized (linkDescriptions) {
428 if (linkDescriptions.isEmpty()) {
429 // never seen such link before. keeping timestamp for record
430 removedLinks.put(key, timestamp);
431 return null;
432 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700433 // accept removal request if given timestamp is newer than
434 // the latest Timestamp from Primary provider
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700435 Timestamped<LinkDescription> prim = getPrimaryDescription(linkDescriptions);
436 if (!isMoreRecent(timestamp, prim)) {
437 // outdated remove request, ignore
Madan Jampani2ff05592014-10-10 15:42:47 -0700438 return null;
439 }
440 removedLinks.put(key, timestamp);
441 Link link = links.remove(key);
442 linkDescriptions.clear();
443 if (link != null) {
444 srcLinks.remove(link.src().deviceId(), key);
445 dstLinks.remove(link.dst().deviceId(), key);
446 return new LinkEvent(LINK_REMOVED, link);
447 }
448 return null;
449 }
450 }
451
452 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
453 return synchronizedSetMultimap(HashMultimap.<K, V>create());
454 }
455
456 /**
457 * @return primary ProviderID, or randomly chosen one if none exists
458 */
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700459 private static ProviderId pickBaseProviderId(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700460 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700461
462 ProviderId fallBackPrimary = null;
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700463 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700464 if (!e.getKey().isAncillary()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700465 // found primary
Madan Jampani2ff05592014-10-10 15:42:47 -0700466 return e.getKey();
467 } else if (fallBackPrimary == null) {
468 // pick randomly as a fallback in case there is no primary
469 fallBackPrimary = e.getKey();
470 }
471 }
472 return fallBackPrimary;
473 }
474
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700475 // Guarded by linkDescs value (=locking each Link)
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700476 private Link composeLink(Map<ProviderId, Timestamped<LinkDescription>> descs) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700477 ProviderId baseProviderId = pickBaseProviderId(descs);
478 Timestamped<LinkDescription> base = descs.get(baseProviderId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700479
480 ConnectPoint src = base.value().src();
481 ConnectPoint dst = base.value().dst();
482 Type type = base.value().type();
483 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
484 annotations = merge(annotations, base.value().annotations());
485
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700486 for (Entry<ProviderId, Timestamped<LinkDescription>> e : descs.entrySet()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700487 if (baseProviderId.equals(e.getKey())) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700488 continue;
489 }
490
491 // TODO: should keep track of Description timestamp
492 // and only merge conflicting keys when timestamp is newer
493 // Currently assuming there will never be a key conflict between
494 // providers
495
496 // annotation merging. not so efficient, should revisit later
497 annotations = merge(annotations, e.getValue().value().annotations());
498 }
499
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700500 return new DefaultLink(baseProviderId, src, dst, type, annotations);
Madan Jampani2ff05592014-10-10 15:42:47 -0700501 }
502
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700503 private Map<ProviderId, Timestamped<LinkDescription>> getOrCreateLinkDescriptions(LinkKey key) {
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700504 Map<ProviderId, Timestamped<LinkDescription>> r;
505 r = linkDescs.get(key);
506 if (r != null) {
507 return r;
508 }
509 r = new HashMap<>();
510 final Map<ProviderId, Timestamped<LinkDescription>> concurrentlyAdded;
511 concurrentlyAdded = linkDescs.putIfAbsent(key, r);
512 if (concurrentlyAdded != null) {
513 return concurrentlyAdded;
514 } else {
515 return r;
516 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700517 }
518
519 private final Function<LinkKey, Link> lookupLink = new LookupLink();
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700520 /**
521 * Returns a Function to lookup Link instance using LinkKey from cache.
522 * @return
523 */
Madan Jampani2ff05592014-10-10 15:42:47 -0700524 private Function<LinkKey, Link> lookupLink() {
525 return lookupLink;
526 }
527
528 private final class LookupLink implements Function<LinkKey, Link> {
529 @Override
530 public Link apply(LinkKey input) {
Yuta HIGUCHI023295a2014-10-15 23:29:46 -0700531 if (input == null) {
532 return null;
533 } else {
534 return links.get(input);
535 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700536 }
537 }
538
Madan Jampani2ff05592014-10-10 15:42:47 -0700539 private void notifyDelegateIfNotNull(LinkEvent event) {
540 if (event != null) {
541 notifyDelegate(event);
542 }
543 }
544
Madan Jampani2ff05592014-10-10 15:42:47 -0700545 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
546 ClusterMessage message = new ClusterMessage(
547 clusterService.getLocalNode().id(),
548 subject,
549 SERIALIZER.encode(event));
550 clusterCommunicator.broadcast(message);
551 }
552
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700553 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
554 ClusterMessage message = new ClusterMessage(
555 clusterService.getLocalNode().id(),
556 subject,
557 SERIALIZER.encode(event));
558 clusterCommunicator.unicast(message, recipient);
Madan Jampania97e8202014-10-10 17:01:33 -0700559 }
560
Madan Jampani2ff05592014-10-10 15:42:47 -0700561 private void notifyPeers(InternalLinkEvent event) throws IOException {
562 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
563 }
564
565 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
566 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
567 }
568
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700569 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700570 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700571 try {
572 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
573 } catch (IOException e) {
574 log.debug("Failed to notify peer {} with message {}", peer, event);
575 }
Madan Jampania97e8202014-10-10 17:01:33 -0700576 }
577
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700578 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700579 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700580 try {
581 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
582 } catch (IOException e) {
583 log.debug("Failed to notify peer {} with message {}", peer, event);
584 }
Madan Jampania97e8202014-10-10 17:01:33 -0700585 }
586
587 private final class SendAdvertisementTask implements Runnable {
588
589 @Override
590 public void run() {
591 if (Thread.currentThread().isInterrupted()) {
592 log.info("Interrupted, quitting");
593 return;
594 }
595
596 try {
597 final NodeId self = clusterService.getLocalNode().id();
598 Set<ControllerNode> nodes = clusterService.getNodes();
599
600 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
601 .transform(toNodeId())
602 .toList();
603
604 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -0700605 log.debug("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700606 return;
607 }
608
609 NodeId peer;
610 do {
611 int idx = RandomUtils.nextInt(0, nodeIds.size());
612 peer = nodeIds.get(idx);
613 } while (peer.equals(self));
614
615 LinkAntiEntropyAdvertisement ad = createAdvertisement();
616
617 if (Thread.currentThread().isInterrupted()) {
618 log.info("Interrupted, quitting");
619 return;
620 }
621
622 try {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700623 unicastMessage(peer, LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
624 } catch (IOException e) {
625 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Madan Jampania97e8202014-10-10 17:01:33 -0700626 return;
627 }
628 } catch (Exception e) {
629 // catch all Exception to avoid Scheduled task being suppressed.
630 log.error("Exception thrown while sending advertisement", e);
631 }
632 }
633 }
634
635 private LinkAntiEntropyAdvertisement createAdvertisement() {
636 final NodeId self = clusterService.getLocalNode().id();
637
638 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
639 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
640
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700641 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
Madan Jampania97e8202014-10-10 17:01:33 -0700642 provs : linkDescs.entrySet()) {
643
644 final LinkKey linkKey = provs.getKey();
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700645 final Map<ProviderId, Timestamped<LinkDescription>> linkDesc = provs.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700646 synchronized (linkDesc) {
647 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
648 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
649 }
650 }
651 }
652
653 linkTombstones.putAll(removedLinks);
654
655 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
656 }
657
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700658 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement ad) {
Madan Jampania97e8202014-10-10 17:01:33 -0700659
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700660 final NodeId sender = ad.sender();
661 boolean localOutdated = false;
Madan Jampania97e8202014-10-10 17:01:33 -0700662
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700663 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
664 l : linkDescs.entrySet()) {
Madan Jampania97e8202014-10-10 17:01:33 -0700665
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700666 final LinkKey key = l.getKey();
667 final Map<ProviderId, Timestamped<LinkDescription>> link = l.getValue();
668 synchronized (link) {
669 Timestamp localLatest = removedLinks.get(key);
Madan Jampania97e8202014-10-10 17:01:33 -0700670
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700671 for (Entry<ProviderId, Timestamped<LinkDescription>> p : link.entrySet()) {
672 final ProviderId providerId = p.getKey();
673 final Timestamped<LinkDescription> pDesc = p.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700674
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700675 final LinkFragmentId fragId = new LinkFragmentId(key, providerId);
676 // remote
677 Timestamp remoteTimestamp = ad.linkTimestamps().get(fragId);
678 if (remoteTimestamp == null) {
679 remoteTimestamp = ad.linkTombstones().get(key);
680 }
681 if (remoteTimestamp == null ||
682 pDesc.isNewer(remoteTimestamp)) {
683 // I have more recent link description. update peer.
684 notifyPeer(sender, new InternalLinkEvent(providerId, pDesc));
685 } else {
686 final Timestamp remoteLive = ad.linkTimestamps().get(fragId);
687 if (remoteLive != null &&
688 remoteLive.compareTo(pDesc.timestamp()) > 0) {
689 // I have something outdated
690 localOutdated = true;
691 }
692 }
693
694 // search local latest along the way
695 if (localLatest == null ||
696 pDesc.isNewer(localLatest)) {
697 localLatest = pDesc.timestamp();
698 }
699 }
700 // Tests if remote remove is more recent then local latest.
701 final Timestamp remoteRemove = ad.linkTombstones().get(key);
702 if (remoteRemove != null) {
703 if (localLatest != null &&
704 localLatest.compareTo(remoteRemove) < 0) {
705 // remote remove is more recent
706 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
707 }
708 }
Madan Jampania97e8202014-10-10 17:01:33 -0700709 }
710 }
711
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700712 // populate remove info if not known locally
713 for (Entry<LinkKey, Timestamp> remoteRm : ad.linkTombstones().entrySet()) {
714 final LinkKey key = remoteRm.getKey();
715 final Timestamp remoteRemove = remoteRm.getValue();
716 // relying on removeLinkInternal to ignore stale info
717 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
718 }
Madan Jampania97e8202014-10-10 17:01:33 -0700719
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700720 if (localOutdated) {
721 // send back advertisement to speed up convergence
722 try {
723 unicastMessage(sender, LINK_ANTI_ENTROPY_ADVERTISEMENT,
724 createAdvertisement());
725 } catch (IOException e) {
726 log.debug("Failed to send back active advertisement");
Madan Jampania97e8202014-10-10 17:01:33 -0700727 }
728 }
729 }
730
Madan Jampani2ff05592014-10-10 15:42:47 -0700731 private class InternalLinkEventListener implements ClusterMessageHandler {
732 @Override
733 public void handle(ClusterMessage message) {
734
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700735 log.trace("Received link event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700736 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
737
738 ProviderId providerId = event.providerId();
739 Timestamped<LinkDescription> linkDescription = event.linkDescription();
740
741 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
742 }
743 }
744
745 private class InternalLinkRemovedEventListener implements ClusterMessageHandler {
746 @Override
747 public void handle(ClusterMessage message) {
748
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700749 log.trace("Received link removed event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700750 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
751
752 LinkKey linkKey = event.linkKey();
753 Timestamp timestamp = event.timestamp();
754
755 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
756 }
757 }
Madan Jampania97e8202014-10-10 17:01:33 -0700758
759 private final class InternalLinkAntiEntropyAdvertisementListener implements ClusterMessageHandler {
760
761 @Override
762 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -0700763 log.debug("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
Madan Jampania97e8202014-10-10 17:01:33 -0700764 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
765 handleAntiEntropyAdvertisement(advertisement);
766 }
767 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700768}