blob: 9a2ed0ac0db32bc989509171d36ba188a5dda9c3 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Madan Jampani2ff05592014-10-10 15:42:47 -070016package org.onlab.onos.store.link.impl;
17
18import com.google.common.base.Function;
Madan Jampani2ff05592014-10-10 15:42:47 -070019import com.google.common.collect.FluentIterable;
20import com.google.common.collect.HashMultimap;
Madan Jampania97e8202014-10-10 17:01:33 -070021import com.google.common.collect.ImmutableList;
Madan Jampani2ff05592014-10-10 15:42:47 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.SetMultimap;
24
Madan Jampania97e8202014-10-10 17:01:33 -070025import org.apache.commons.lang3.RandomUtils;
Madan Jampani2ff05592014-10-10 15:42:47 -070026import org.apache.felix.scr.annotations.Activate;
27import org.apache.felix.scr.annotations.Component;
28import org.apache.felix.scr.annotations.Deactivate;
29import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
31import org.apache.felix.scr.annotations.Service;
32import org.onlab.onos.cluster.ClusterService;
Madan Jampania97e8202014-10-10 17:01:33 -070033import org.onlab.onos.cluster.ControllerNode;
34import org.onlab.onos.cluster.NodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070035import org.onlab.onos.net.AnnotationsUtil;
36import org.onlab.onos.net.ConnectPoint;
37import org.onlab.onos.net.DefaultAnnotations;
38import org.onlab.onos.net.DefaultLink;
39import org.onlab.onos.net.DeviceId;
40import org.onlab.onos.net.Link;
Madan Jampani2ff05592014-10-10 15:42:47 -070041import org.onlab.onos.net.Link.Type;
42import org.onlab.onos.net.LinkKey;
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -070043import org.onlab.onos.net.SparseAnnotations;
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -070044import org.onlab.onos.net.device.DeviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -070045import org.onlab.onos.net.link.DefaultLinkDescription;
46import org.onlab.onos.net.link.LinkDescription;
47import org.onlab.onos.net.link.LinkEvent;
48import org.onlab.onos.net.link.LinkStore;
49import org.onlab.onos.net.link.LinkStoreDelegate;
50import org.onlab.onos.net.provider.ProviderId;
51import org.onlab.onos.store.AbstractStore;
Madan Jampani2ff05592014-10-10 15:42:47 -070052import org.onlab.onos.store.Timestamp;
53import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
54import org.onlab.onos.store.cluster.messaging.ClusterMessage;
55import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
56import org.onlab.onos.store.cluster.messaging.MessageSubject;
Yuta HIGUCHIeecee552014-10-16 14:09:01 -070057import org.onlab.onos.store.impl.Timestamped;
Madan Jampani2ff05592014-10-10 15:42:47 -070058import org.onlab.onos.store.serializers.DistributedStoreSerializers;
59import org.onlab.onos.store.serializers.KryoSerializer;
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070060import org.onlab.util.KryoNamespace;
Madan Jampani2ff05592014-10-10 15:42:47 -070061import org.slf4j.Logger;
62
63import java.io.IOException;
64import java.util.Collections;
Madan Jampania97e8202014-10-10 17:01:33 -070065import java.util.HashMap;
Madan Jampani2ff05592014-10-10 15:42:47 -070066import java.util.HashSet;
67import java.util.Map;
68import java.util.Set;
69import java.util.Map.Entry;
70import java.util.concurrent.ConcurrentHashMap;
71import java.util.concurrent.ConcurrentMap;
Madan Jampania97e8202014-10-10 17:01:33 -070072import java.util.concurrent.ScheduledExecutorService;
73import java.util.concurrent.TimeUnit;
Madan Jampani2ff05592014-10-10 15:42:47 -070074
Madan Jampania97e8202014-10-10 17:01:33 -070075import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
76import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Madan Jampani2ff05592014-10-10 15:42:47 -070077import static org.onlab.onos.net.DefaultAnnotations.union;
78import static org.onlab.onos.net.DefaultAnnotations.merge;
79import static org.onlab.onos.net.Link.Type.DIRECT;
80import static org.onlab.onos.net.Link.Type.INDIRECT;
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -070081import static org.onlab.onos.net.LinkKey.linkKey;
Madan Jampani2ff05592014-10-10 15:42:47 -070082import static org.onlab.onos.net.link.LinkEvent.Type.*;
Madan Jampania97e8202014-10-10 17:01:33 -070083import static org.onlab.util.Tools.namedThreads;
Madan Jampani2ff05592014-10-10 15:42:47 -070084import static org.slf4j.LoggerFactory.getLogger;
85import static com.google.common.collect.Multimaps.synchronizedSetMultimap;
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -070086import static com.google.common.base.Preconditions.checkNotNull;
Madan Jampani2ff05592014-10-10 15:42:47 -070087import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -070088import static org.onlab.onos.store.link.impl.GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT;
Madan Jampani2ff05592014-10-10 15:42:47 -070089
90/**
91 * Manages inventory of infrastructure links in distributed data store
92 * that uses optimistic replication and gossip based techniques.
93 */
94@Component(immediate = true)
95@Service
96public class GossipLinkStore
97 extends AbstractStore<LinkEvent, LinkStoreDelegate>
98 implements LinkStore {
99
100 private final Logger log = getLogger(getClass());
101
102 // Link inventory
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700103 private final ConcurrentMap<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>> linkDescs =
Madan Jampani2ff05592014-10-10 15:42:47 -0700104 new ConcurrentHashMap<>();
105
106 // Link instance cache
107 private final ConcurrentMap<LinkKey, Link> links = new ConcurrentHashMap<>();
108
109 // Egress and ingress link sets
110 private final SetMultimap<DeviceId, LinkKey> srcLinks = createSynchronizedHashMultiMap();
111 private final SetMultimap<DeviceId, LinkKey> dstLinks = createSynchronizedHashMultiMap();
112
113 // Remove links
114 private final Map<LinkKey, Timestamp> removedLinks = Maps.newHashMap();
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700117 protected DeviceClockService deviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -0700118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected ClusterCommunicationService clusterCommunicator;
121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
123 protected ClusterService clusterService;
124
125 private static final KryoSerializer SERIALIZER = new KryoSerializer() {
126 @Override
127 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700128 serializerPool = KryoNamespace.newBuilder()
Madan Jampani2ff05592014-10-10 15:42:47 -0700129 .register(DistributedStoreSerializers.COMMON)
130 .register(InternalLinkEvent.class)
131 .register(InternalLinkRemovedEvent.class)
Madan Jampanid2054d42014-10-10 17:27:06 -0700132 .register(LinkAntiEntropyAdvertisement.class)
133 .register(LinkFragmentId.class)
Madan Jampani2ff05592014-10-10 15:42:47 -0700134 .build()
135 .populate(1);
136 }
137 };
138
Madan Jampania97e8202014-10-10 17:01:33 -0700139 private ScheduledExecutorService executor;
140
Madan Jampani2ff05592014-10-10 15:42:47 -0700141 @Activate
142 public void activate() {
143
144 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700145 GossipLinkStoreMessageSubjects.LINK_UPDATE,
146 new InternalLinkEventListener());
Madan Jampani2ff05592014-10-10 15:42:47 -0700147 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700148 GossipLinkStoreMessageSubjects.LINK_REMOVED,
149 new InternalLinkRemovedEventListener());
150 clusterCommunicator.addSubscriber(
151 GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT,
152 new InternalLinkAntiEntropyAdvertisementListener());
153
154 executor =
155 newSingleThreadScheduledExecutor(namedThreads("link-anti-entropy-%d"));
156
157 // TODO: Make these configurable
158 long initialDelaySec = 5;
159 long periodSec = 5;
160 // start anti-entropy thread
161 executor.scheduleAtFixedRate(new SendAdvertisementTask(),
162 initialDelaySec, periodSec, TimeUnit.SECONDS);
Madan Jampani2ff05592014-10-10 15:42:47 -0700163
164 log.info("Started");
165 }
166
167 @Deactivate
168 public void deactivate() {
Madan Jampani3ffbb272014-10-13 11:19:37 -0700169
170 executor.shutdownNow();
171 try {
172 if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
173 log.error("Timeout during executor shutdown");
174 }
175 } catch (InterruptedException e) {
176 log.error("Error during executor shutdown", e);
177 }
178
Madan Jampani2ff05592014-10-10 15:42:47 -0700179 linkDescs.clear();
180 links.clear();
181 srcLinks.clear();
182 dstLinks.clear();
183 log.info("Stopped");
184 }
185
186 @Override
187 public int getLinkCount() {
188 return links.size();
189 }
190
191 @Override
192 public Iterable<Link> getLinks() {
193 return Collections.unmodifiableCollection(links.values());
194 }
195
196 @Override
197 public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
198 // lock for iteration
199 synchronized (srcLinks) {
200 return FluentIterable.from(srcLinks.get(deviceId))
201 .transform(lookupLink())
202 .filter(notNull())
203 .toSet();
204 }
205 }
206
207 @Override
208 public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
209 // lock for iteration
210 synchronized (dstLinks) {
211 return FluentIterable.from(dstLinks.get(deviceId))
212 .transform(lookupLink())
213 .filter(notNull())
214 .toSet();
215 }
216 }
217
218 @Override
219 public Link getLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700220 return links.get(linkKey(src, dst));
Madan Jampani2ff05592014-10-10 15:42:47 -0700221 }
222
223 @Override
224 public Set<Link> getEgressLinks(ConnectPoint src) {
225 Set<Link> egress = new HashSet<>();
226 for (LinkKey linkKey : srcLinks.get(src.deviceId())) {
227 if (linkKey.src().equals(src)) {
228 egress.add(links.get(linkKey));
229 }
230 }
231 return egress;
232 }
233
234 @Override
235 public Set<Link> getIngressLinks(ConnectPoint dst) {
236 Set<Link> ingress = new HashSet<>();
237 for (LinkKey linkKey : dstLinks.get(dst.deviceId())) {
238 if (linkKey.dst().equals(dst)) {
239 ingress.add(links.get(linkKey));
240 }
241 }
242 return ingress;
243 }
244
245 @Override
246 public LinkEvent createOrUpdateLink(ProviderId providerId,
247 LinkDescription linkDescription) {
248
249 DeviceId dstDeviceId = linkDescription.dst().deviceId();
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700250 Timestamp newTimestamp = deviceClockService.getTimestamp(dstDeviceId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700251
252 final Timestamped<LinkDescription> deltaDesc = new Timestamped<>(linkDescription, newTimestamp);
253
Yuta HIGUCHI990aecc2014-10-13 22:21:42 -0700254 LinkKey key = linkKey(linkDescription.src(), linkDescription.dst());
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700255 final LinkEvent event;
256 final Timestamped<LinkDescription> mergedDesc;
alshabibdfc7afb2014-10-21 20:13:27 -0700257 Map<ProviderId, Timestamped<LinkDescription>> map = getOrCreateLinkDescriptions(key);
258 synchronized (map) {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700259 event = createOrUpdateLinkInternal(providerId, deltaDesc);
alshabibdfc7afb2014-10-21 20:13:27 -0700260 mergedDesc = map.get(providerId);
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700261 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700262
alshabibdfc7afb2014-10-21 20:13:27 -0700263
264
Madan Jampani2ff05592014-10-10 15:42:47 -0700265 if (event != null) {
266 log.info("Notifying peers of a link update topology event from providerId: "
267 + "{} between src: {} and dst: {}",
268 providerId, linkDescription.src(), linkDescription.dst());
269 try {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700270 notifyPeers(new InternalLinkEvent(providerId, mergedDesc));
Madan Jampani2ff05592014-10-10 15:42:47 -0700271 } catch (IOException e) {
272 log.info("Failed to notify peers of a link update topology event from providerId: "
alshabibdfc7afb2014-10-21 20:13:27 -0700273 + "{} between src: {} and dst: {}",
274 providerId, linkDescription.src(), linkDescription.dst());
Madan Jampani2ff05592014-10-10 15:42:47 -0700275 }
276 }
277 return event;
278 }
279
280 private LinkEvent createOrUpdateLinkInternal(
281 ProviderId providerId,
282 Timestamped<LinkDescription> linkDescription) {
283
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700284 final LinkKey key = linkKey(linkDescription.value().src(),
285 linkDescription.value().dst());
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700286 Map<ProviderId, Timestamped<LinkDescription>> descs = getOrCreateLinkDescriptions(key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700287
288 synchronized (descs) {
289 // if the link was previously removed, we should proceed if and
290 // only if this request is more recent.
291 Timestamp linkRemovedTimestamp = removedLinks.get(key);
292 if (linkRemovedTimestamp != null) {
293 if (linkDescription.isNewer(linkRemovedTimestamp)) {
294 removedLinks.remove(key);
295 } else {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700296 log.trace("Link {} was already removed ignoring.", key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700297 return null;
298 }
299 }
300
301 final Link oldLink = links.get(key);
302 // update description
303 createOrUpdateLinkDescription(descs, providerId, linkDescription);
304 final Link newLink = composeLink(descs);
305 if (oldLink == null) {
306 return createLink(key, newLink);
307 }
308 return updateLink(key, oldLink, newLink);
309 }
310 }
311
312 // Guarded by linkDescs value (=locking each Link)
313 private Timestamped<LinkDescription> createOrUpdateLinkDescription(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700314 Map<ProviderId, Timestamped<LinkDescription>> descs,
Madan Jampani2ff05592014-10-10 15:42:47 -0700315 ProviderId providerId,
316 Timestamped<LinkDescription> linkDescription) {
317
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700318 // merge existing annotations
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700319 Timestamped<LinkDescription> existingLinkDescription = descs.get(providerId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700320 if (existingLinkDescription != null && existingLinkDescription.isNewer(linkDescription)) {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700321 log.trace("local info is more up-to-date, ignoring {}.", linkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700322 return null;
323 }
324 Timestamped<LinkDescription> newLinkDescription = linkDescription;
325 if (existingLinkDescription != null) {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700326 // we only allow transition from INDIRECT -> DIRECT
327 final Type newType;
328 if (existingLinkDescription.value().type() == DIRECT) {
329 newType = DIRECT;
330 } else {
331 newType = linkDescription.value().type();
332 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700333 SparseAnnotations merged = union(existingLinkDescription.value().annotations(),
334 linkDescription.value().annotations());
335 newLinkDescription = new Timestamped<LinkDescription>(
336 new DefaultLinkDescription(
337 linkDescription.value().src(),
338 linkDescription.value().dst(),
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700339 newType, merged),
Madan Jampani2ff05592014-10-10 15:42:47 -0700340 linkDescription.timestamp());
341 }
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700342 return descs.put(providerId, newLinkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700343 }
344
345 // Creates and stores the link and returns the appropriate event.
346 // Guarded by linkDescs value (=locking each Link)
347 private LinkEvent createLink(LinkKey key, Link newLink) {
348
349 if (newLink.providerId().isAncillary()) {
350 // TODO: revisit ancillary only Link handling
351
352 // currently treating ancillary only as down (not visible outside)
353 return null;
354 }
355
356 links.put(key, newLink);
357 srcLinks.put(newLink.src().deviceId(), key);
358 dstLinks.put(newLink.dst().deviceId(), key);
359 return new LinkEvent(LINK_ADDED, newLink);
360 }
361
362 // Updates, if necessary the specified link and returns the appropriate event.
363 // Guarded by linkDescs value (=locking each Link)
364 private LinkEvent updateLink(LinkKey key, Link oldLink, Link newLink) {
365
366 if (newLink.providerId().isAncillary()) {
367 // TODO: revisit ancillary only Link handling
368
369 // currently treating ancillary only as down (not visible outside)
370 return null;
371 }
372
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700373 // Note: INDIRECT -> DIRECT transition only
374 // so that BDDP discovered Link will not overwrite LDDP Link
Madan Jampani2ff05592014-10-10 15:42:47 -0700375 if ((oldLink.type() == INDIRECT && newLink.type() == DIRECT) ||
376 !AnnotationsUtil.isEqual(oldLink.annotations(), newLink.annotations())) {
377
378 links.put(key, newLink);
379 // strictly speaking following can be ommitted
380 srcLinks.put(oldLink.src().deviceId(), key);
381 dstLinks.put(oldLink.dst().deviceId(), key);
382 return new LinkEvent(LINK_UPDATED, newLink);
383 }
384 return null;
385 }
386
387 @Override
388 public LinkEvent removeLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700389 final LinkKey key = linkKey(src, dst);
Madan Jampani2ff05592014-10-10 15:42:47 -0700390
391 DeviceId dstDeviceId = dst.deviceId();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700392 Timestamp timestamp = null;
393 try {
394 timestamp = deviceClockService.getTimestamp(dstDeviceId);
395 } catch (IllegalStateException e) {
396 //there are times when this is called before mastership
397 // handoff correctly completes.
398 return null;
399 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700400
401 LinkEvent event = removeLinkInternal(key, timestamp);
402
403 if (event != null) {
404 log.info("Notifying peers of a link removed topology event for a link "
405 + "between src: {} and dst: {}", src, dst);
406 try {
407 notifyPeers(new InternalLinkRemovedEvent(key, timestamp));
408 } catch (IOException e) {
409 log.error("Failed to notify peers of a link removed topology event for a link "
410 + "between src: {} and dst: {}", src, dst);
411 }
412 }
413 return event;
414 }
415
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700416 private static Timestamped<LinkDescription> getPrimaryDescription(
417 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
418
Madan Jampani2ff05592014-10-10 15:42:47 -0700419 synchronized (linkDescriptions) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700420 for (Entry<ProviderId, Timestamped<LinkDescription>>
421 e : linkDescriptions.entrySet()) {
422
423 if (!e.getKey().isAncillary()) {
424 return e.getValue();
425 }
426 }
427 }
428 return null;
429 }
430
431
432 // TODO: consider slicing out as Timestamp utils
433 /**
434 * Checks is timestamp is more recent than timestamped object.
435 *
436 * @param timestamp to check if this is more recent then other
437 * @param timestamped object to be tested against
438 * @return true if {@code timestamp} is more recent than {@code timestamped}
439 * or {@code timestamped is null}
440 */
441 private static boolean isMoreRecent(Timestamp timestamp, Timestamped<?> timestamped) {
442 checkNotNull(timestamp);
443 if (timestamped == null) {
444 return true;
445 }
446 return timestamp.compareTo(timestamped.timestamp()) > 0;
447 }
448
449 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
450 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions
451 = getOrCreateLinkDescriptions(key);
452
453 synchronized (linkDescriptions) {
454 if (linkDescriptions.isEmpty()) {
455 // never seen such link before. keeping timestamp for record
456 removedLinks.put(key, timestamp);
457 return null;
458 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700459 // accept removal request if given timestamp is newer than
460 // the latest Timestamp from Primary provider
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700461 Timestamped<LinkDescription> prim = getPrimaryDescription(linkDescriptions);
462 if (!isMoreRecent(timestamp, prim)) {
463 // outdated remove request, ignore
Madan Jampani2ff05592014-10-10 15:42:47 -0700464 return null;
465 }
466 removedLinks.put(key, timestamp);
467 Link link = links.remove(key);
468 linkDescriptions.clear();
469 if (link != null) {
470 srcLinks.remove(link.src().deviceId(), key);
471 dstLinks.remove(link.dst().deviceId(), key);
472 return new LinkEvent(LINK_REMOVED, link);
473 }
474 return null;
475 }
476 }
477
478 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
479 return synchronizedSetMultimap(HashMultimap.<K, V>create());
480 }
481
482 /**
483 * @return primary ProviderID, or randomly chosen one if none exists
484 */
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700485 private static ProviderId pickBaseProviderId(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700486 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700487
488 ProviderId fallBackPrimary = null;
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700489 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700490 if (!e.getKey().isAncillary()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700491 // found primary
Madan Jampani2ff05592014-10-10 15:42:47 -0700492 return e.getKey();
493 } else if (fallBackPrimary == null) {
494 // pick randomly as a fallback in case there is no primary
495 fallBackPrimary = e.getKey();
496 }
497 }
498 return fallBackPrimary;
499 }
500
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700501 // Guarded by linkDescs value (=locking each Link)
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700502 private Link composeLink(Map<ProviderId, Timestamped<LinkDescription>> descs) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700503 ProviderId baseProviderId = pickBaseProviderId(descs);
504 Timestamped<LinkDescription> base = descs.get(baseProviderId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700505
506 ConnectPoint src = base.value().src();
507 ConnectPoint dst = base.value().dst();
508 Type type = base.value().type();
509 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
510 annotations = merge(annotations, base.value().annotations());
511
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700512 for (Entry<ProviderId, Timestamped<LinkDescription>> e : descs.entrySet()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700513 if (baseProviderId.equals(e.getKey())) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700514 continue;
515 }
516
517 // TODO: should keep track of Description timestamp
518 // and only merge conflicting keys when timestamp is newer
519 // Currently assuming there will never be a key conflict between
520 // providers
521
522 // annotation merging. not so efficient, should revisit later
523 annotations = merge(annotations, e.getValue().value().annotations());
524 }
525
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700526 return new DefaultLink(baseProviderId, src, dst, type, annotations);
Madan Jampani2ff05592014-10-10 15:42:47 -0700527 }
528
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700529 private Map<ProviderId, Timestamped<LinkDescription>> getOrCreateLinkDescriptions(LinkKey key) {
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700530 Map<ProviderId, Timestamped<LinkDescription>> r;
531 r = linkDescs.get(key);
532 if (r != null) {
533 return r;
534 }
535 r = new HashMap<>();
536 final Map<ProviderId, Timestamped<LinkDescription>> concurrentlyAdded;
537 concurrentlyAdded = linkDescs.putIfAbsent(key, r);
538 if (concurrentlyAdded != null) {
539 return concurrentlyAdded;
540 } else {
541 return r;
542 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700543 }
544
545 private final Function<LinkKey, Link> lookupLink = new LookupLink();
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700546 /**
547 * Returns a Function to lookup Link instance using LinkKey from cache.
548 * @return
549 */
Madan Jampani2ff05592014-10-10 15:42:47 -0700550 private Function<LinkKey, Link> lookupLink() {
551 return lookupLink;
552 }
553
554 private final class LookupLink implements Function<LinkKey, Link> {
555 @Override
556 public Link apply(LinkKey input) {
Yuta HIGUCHI023295a2014-10-15 23:29:46 -0700557 if (input == null) {
558 return null;
559 } else {
560 return links.get(input);
561 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700562 }
563 }
564
Madan Jampani2ff05592014-10-10 15:42:47 -0700565 private void notifyDelegateIfNotNull(LinkEvent event) {
566 if (event != null) {
567 notifyDelegate(event);
568 }
569 }
570
Madan Jampani2ff05592014-10-10 15:42:47 -0700571 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
572 ClusterMessage message = new ClusterMessage(
573 clusterService.getLocalNode().id(),
574 subject,
575 SERIALIZER.encode(event));
576 clusterCommunicator.broadcast(message);
577 }
578
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700579 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
580 ClusterMessage message = new ClusterMessage(
581 clusterService.getLocalNode().id(),
582 subject,
583 SERIALIZER.encode(event));
584 clusterCommunicator.unicast(message, recipient);
Madan Jampania97e8202014-10-10 17:01:33 -0700585 }
586
Madan Jampani2ff05592014-10-10 15:42:47 -0700587 private void notifyPeers(InternalLinkEvent event) throws IOException {
588 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
589 }
590
591 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
592 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
593 }
594
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700595 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700596 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700597 try {
598 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
599 } catch (IOException e) {
600 log.debug("Failed to notify peer {} with message {}", peer, event);
601 }
Madan Jampania97e8202014-10-10 17:01:33 -0700602 }
603
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700604 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700605 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700606 try {
607 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
608 } catch (IOException e) {
609 log.debug("Failed to notify peer {} with message {}", peer, event);
610 }
Madan Jampania97e8202014-10-10 17:01:33 -0700611 }
612
613 private final class SendAdvertisementTask implements Runnable {
614
615 @Override
616 public void run() {
617 if (Thread.currentThread().isInterrupted()) {
618 log.info("Interrupted, quitting");
619 return;
620 }
621
622 try {
623 final NodeId self = clusterService.getLocalNode().id();
624 Set<ControllerNode> nodes = clusterService.getNodes();
625
626 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
627 .transform(toNodeId())
628 .toList();
629
630 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -0700631 log.debug("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700632 return;
633 }
634
635 NodeId peer;
636 do {
637 int idx = RandomUtils.nextInt(0, nodeIds.size());
638 peer = nodeIds.get(idx);
639 } while (peer.equals(self));
640
641 LinkAntiEntropyAdvertisement ad = createAdvertisement();
642
643 if (Thread.currentThread().isInterrupted()) {
644 log.info("Interrupted, quitting");
645 return;
646 }
647
648 try {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700649 unicastMessage(peer, LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
650 } catch (IOException e) {
651 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Madan Jampania97e8202014-10-10 17:01:33 -0700652 return;
653 }
654 } catch (Exception e) {
655 // catch all Exception to avoid Scheduled task being suppressed.
656 log.error("Exception thrown while sending advertisement", e);
657 }
658 }
659 }
660
661 private LinkAntiEntropyAdvertisement createAdvertisement() {
662 final NodeId self = clusterService.getLocalNode().id();
663
664 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
665 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
666
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700667 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
Madan Jampania97e8202014-10-10 17:01:33 -0700668 provs : linkDescs.entrySet()) {
669
670 final LinkKey linkKey = provs.getKey();
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700671 final Map<ProviderId, Timestamped<LinkDescription>> linkDesc = provs.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700672 synchronized (linkDesc) {
673 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
674 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
675 }
676 }
677 }
678
679 linkTombstones.putAll(removedLinks);
680
681 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
682 }
683
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700684 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement ad) {
Madan Jampania97e8202014-10-10 17:01:33 -0700685
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700686 final NodeId sender = ad.sender();
687 boolean localOutdated = false;
Madan Jampania97e8202014-10-10 17:01:33 -0700688
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700689 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
690 l : linkDescs.entrySet()) {
Madan Jampania97e8202014-10-10 17:01:33 -0700691
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700692 final LinkKey key = l.getKey();
693 final Map<ProviderId, Timestamped<LinkDescription>> link = l.getValue();
694 synchronized (link) {
695 Timestamp localLatest = removedLinks.get(key);
Madan Jampania97e8202014-10-10 17:01:33 -0700696
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700697 for (Entry<ProviderId, Timestamped<LinkDescription>> p : link.entrySet()) {
698 final ProviderId providerId = p.getKey();
699 final Timestamped<LinkDescription> pDesc = p.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700700
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700701 final LinkFragmentId fragId = new LinkFragmentId(key, providerId);
702 // remote
703 Timestamp remoteTimestamp = ad.linkTimestamps().get(fragId);
704 if (remoteTimestamp == null) {
705 remoteTimestamp = ad.linkTombstones().get(key);
706 }
707 if (remoteTimestamp == null ||
708 pDesc.isNewer(remoteTimestamp)) {
709 // I have more recent link description. update peer.
710 notifyPeer(sender, new InternalLinkEvent(providerId, pDesc));
711 } else {
712 final Timestamp remoteLive = ad.linkTimestamps().get(fragId);
713 if (remoteLive != null &&
714 remoteLive.compareTo(pDesc.timestamp()) > 0) {
715 // I have something outdated
716 localOutdated = true;
717 }
718 }
719
720 // search local latest along the way
721 if (localLatest == null ||
722 pDesc.isNewer(localLatest)) {
723 localLatest = pDesc.timestamp();
724 }
725 }
726 // Tests if remote remove is more recent then local latest.
727 final Timestamp remoteRemove = ad.linkTombstones().get(key);
728 if (remoteRemove != null) {
729 if (localLatest != null &&
730 localLatest.compareTo(remoteRemove) < 0) {
731 // remote remove is more recent
732 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
733 }
734 }
Madan Jampania97e8202014-10-10 17:01:33 -0700735 }
736 }
737
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700738 // populate remove info if not known locally
739 for (Entry<LinkKey, Timestamp> remoteRm : ad.linkTombstones().entrySet()) {
740 final LinkKey key = remoteRm.getKey();
741 final Timestamp remoteRemove = remoteRm.getValue();
742 // relying on removeLinkInternal to ignore stale info
743 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
744 }
Madan Jampania97e8202014-10-10 17:01:33 -0700745
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700746 if (localOutdated) {
747 // send back advertisement to speed up convergence
748 try {
749 unicastMessage(sender, LINK_ANTI_ENTROPY_ADVERTISEMENT,
750 createAdvertisement());
751 } catch (IOException e) {
752 log.debug("Failed to send back active advertisement");
Madan Jampania97e8202014-10-10 17:01:33 -0700753 }
754 }
755 }
756
Madan Jampani2ff05592014-10-10 15:42:47 -0700757 private class InternalLinkEventListener implements ClusterMessageHandler {
758 @Override
759 public void handle(ClusterMessage message) {
760
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700761 log.trace("Received link event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700762 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
763
764 ProviderId providerId = event.providerId();
765 Timestamped<LinkDescription> linkDescription = event.linkDescription();
766
767 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
768 }
769 }
770
771 private class InternalLinkRemovedEventListener implements ClusterMessageHandler {
772 @Override
773 public void handle(ClusterMessage message) {
774
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700775 log.trace("Received link removed event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700776 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
777
778 LinkKey linkKey = event.linkKey();
779 Timestamp timestamp = event.timestamp();
780
781 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
782 }
783 }
Madan Jampania97e8202014-10-10 17:01:33 -0700784
785 private final class InternalLinkAntiEntropyAdvertisementListener implements ClusterMessageHandler {
786
787 @Override
788 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -0700789 log.debug("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
Madan Jampania97e8202014-10-10 17:01:33 -0700790 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
791 handleAntiEntropyAdvertisement(advertisement);
792 }
793 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700794}