blob: e44737cd612375e7a66ff1f080aceff703d6b73e [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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.link.impl;
Madan Jampani2ff05592014-10-10 15:42:47 -070017
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.SetMultimap;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080023
Madan Jampania97e8202014-10-10 17:01:33 -070024import org.apache.commons.lang3.RandomUtils;
Madan Jampani2ff05592014-10-10 15:42:47 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.ControllerNode;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.net.AnnotationKeys;
35import org.onosproject.net.AnnotationsUtil;
36import org.onosproject.net.ConnectPoint;
37import org.onosproject.net.DefaultAnnotations;
38import org.onosproject.net.DefaultLink;
39import org.onosproject.net.DeviceId;
40import org.onosproject.net.Link;
41import org.onosproject.net.Link.Type;
42import org.onosproject.net.LinkKey;
43import org.onosproject.net.SparseAnnotations;
44import org.onosproject.net.device.DeviceClockService;
45import org.onosproject.net.link.DefaultLinkDescription;
46import org.onosproject.net.link.LinkDescription;
47import org.onosproject.net.link.LinkEvent;
48import org.onosproject.net.link.LinkStore;
49import org.onosproject.net.link.LinkStoreDelegate;
50import org.onosproject.net.provider.ProviderId;
51import org.onosproject.store.AbstractStore;
52import org.onosproject.store.Timestamp;
53import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
54import org.onosproject.store.cluster.messaging.ClusterMessage;
55import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
56import org.onosproject.store.cluster.messaging.MessageSubject;
57import org.onosproject.store.impl.Timestamped;
58import org.onosproject.store.serializers.KryoSerializer;
59import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
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;
Thomas Vachuska57126fe2014-11-11 17:13:24 -080068import java.util.Map.Entry;
Thomas Vachuska29a6a782014-11-10 21:31:41 -080069import java.util.Objects;
Madan Jampani2ff05592014-10-10 15:42:47 -070070import java.util.Set;
Madan Jampani2ff05592014-10-10 15:42:47 -070071import java.util.concurrent.ConcurrentHashMap;
72import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080073import java.util.concurrent.ExecutorService;
74import java.util.concurrent.Executors;
Madan Jampania97e8202014-10-10 17:01:33 -070075import java.util.concurrent.ScheduledExecutorService;
76import java.util.concurrent.TimeUnit;
Madan Jampani2ff05592014-10-10 15:42:47 -070077
Thomas Vachuska57126fe2014-11-11 17:13:24 -080078import static com.google.common.base.Preconditions.checkNotNull;
79import static com.google.common.base.Predicates.notNull;
80import static com.google.common.collect.Multimaps.synchronizedSetMultimap;
Madan Jampania97e8202014-10-10 17:01:33 -070081import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Brian O'Connorabafb502014-12-02 22:26:20 -080082import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
83import static org.onosproject.net.DefaultAnnotations.merge;
84import static org.onosproject.net.DefaultAnnotations.union;
85import static org.onosproject.net.Link.State.ACTIVE;
86import static org.onosproject.net.Link.State.INACTIVE;
87import static org.onosproject.net.Link.Type.DIRECT;
88import static org.onosproject.net.Link.Type.INDIRECT;
89import static org.onosproject.net.LinkKey.linkKey;
90import static org.onosproject.net.link.LinkEvent.Type.*;
91import static org.onosproject.store.link.impl.GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080092import static org.onlab.util.Tools.minPriority;
Madan Jampania97e8202014-10-10 17:01:33 -070093import static org.onlab.util.Tools.namedThreads;
Madan Jampani2ff05592014-10-10 15:42:47 -070094import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani2ff05592014-10-10 15:42:47 -070095
96/**
97 * Manages inventory of infrastructure links in distributed data store
98 * that uses optimistic replication and gossip based techniques.
99 */
100@Component(immediate = true)
101@Service
102public class GossipLinkStore
103 extends AbstractStore<LinkEvent, LinkStoreDelegate>
104 implements LinkStore {
105
106 private final Logger log = getLogger(getClass());
107
108 // Link inventory
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700109 private final ConcurrentMap<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>> linkDescs =
Madan Jampani2ff05592014-10-10 15:42:47 -0700110 new ConcurrentHashMap<>();
111
112 // Link instance cache
113 private final ConcurrentMap<LinkKey, Link> links = new ConcurrentHashMap<>();
114
115 // Egress and ingress link sets
116 private final SetMultimap<DeviceId, LinkKey> srcLinks = createSynchronizedHashMultiMap();
117 private final SetMultimap<DeviceId, LinkKey> dstLinks = createSynchronizedHashMultiMap();
118
119 // Remove links
Yuta HIGUCHIb9125562014-12-01 23:28:22 -0800120 private final Map<LinkKey, Timestamp> removedLinks = new ConcurrentHashMap<>();
Madan Jampani2ff05592014-10-10 15:42:47 -0700121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700123 protected DeviceClockService deviceClockService;
Madan Jampani2ff05592014-10-10 15:42:47 -0700124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
126 protected ClusterCommunicationService clusterCommunicator;
127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected ClusterService clusterService;
130
Yuta HIGUCHI3e5d11a2014-11-04 14:16:44 -0800131 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Madan Jampani2ff05592014-10-10 15:42:47 -0700132 @Override
133 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700134 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800135 .register(DistributedStoreSerializers.STORE_COMMON)
136 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
Madan Jampani2ff05592014-10-10 15:42:47 -0700137 .register(InternalLinkEvent.class)
138 .register(InternalLinkRemovedEvent.class)
Madan Jampanid2054d42014-10-10 17:27:06 -0700139 .register(LinkAntiEntropyAdvertisement.class)
140 .register(LinkFragmentId.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800141 .build();
Madan Jampani2ff05592014-10-10 15:42:47 -0700142 }
143 };
144
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800145 private ExecutorService executor;
146
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800147 private ScheduledExecutorService backgroundExecutors;
Madan Jampania97e8202014-10-10 17:01:33 -0700148
Madan Jampani2ff05592014-10-10 15:42:47 -0700149 @Activate
150 public void activate() {
151
152 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700153 GossipLinkStoreMessageSubjects.LINK_UPDATE,
154 new InternalLinkEventListener());
Madan Jampani2ff05592014-10-10 15:42:47 -0700155 clusterCommunicator.addSubscriber(
Madan Jampania97e8202014-10-10 17:01:33 -0700156 GossipLinkStoreMessageSubjects.LINK_REMOVED,
157 new InternalLinkRemovedEventListener());
158 clusterCommunicator.addSubscriber(
159 GossipLinkStoreMessageSubjects.LINK_ANTI_ENTROPY_ADVERTISEMENT,
160 new InternalLinkAntiEntropyAdvertisementListener());
161
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800162 executor = Executors.newCachedThreadPool(namedThreads("link-fg-%d"));
163
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800164 backgroundExecutors =
165 newSingleThreadScheduledExecutor(minPriority(namedThreads("link-bg-%d")));
Madan Jampania97e8202014-10-10 17:01:33 -0700166
Madan Jampania97e8202014-10-10 17:01:33 -0700167 long initialDelaySec = 5;
168 long periodSec = 5;
169 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800170 backgroundExecutors.scheduleAtFixedRate(new SendAdvertisementTask(),
Madan Jampania97e8202014-10-10 17:01:33 -0700171 initialDelaySec, periodSec, TimeUnit.SECONDS);
Madan Jampani2ff05592014-10-10 15:42:47 -0700172
173 log.info("Started");
174 }
175
176 @Deactivate
177 public void deactivate() {
Madan Jampani3ffbb272014-10-13 11:19:37 -0700178
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800179 executor.shutdownNow();
180
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800181 backgroundExecutors.shutdownNow();
Madan Jampani3ffbb272014-10-13 11:19:37 -0700182 try {
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800183 if (!backgroundExecutors.awaitTermination(5, TimeUnit.SECONDS)) {
Madan Jampani3ffbb272014-10-13 11:19:37 -0700184 log.error("Timeout during executor shutdown");
185 }
186 } catch (InterruptedException e) {
187 log.error("Error during executor shutdown", e);
188 }
189
Madan Jampani2ff05592014-10-10 15:42:47 -0700190 linkDescs.clear();
191 links.clear();
192 srcLinks.clear();
193 dstLinks.clear();
194 log.info("Stopped");
195 }
196
197 @Override
198 public int getLinkCount() {
199 return links.size();
200 }
201
202 @Override
203 public Iterable<Link> getLinks() {
204 return Collections.unmodifiableCollection(links.values());
205 }
206
207 @Override
208 public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
209 // lock for iteration
210 synchronized (srcLinks) {
211 return FluentIterable.from(srcLinks.get(deviceId))
212 .transform(lookupLink())
213 .filter(notNull())
214 .toSet();
215 }
216 }
217
218 @Override
219 public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
220 // lock for iteration
221 synchronized (dstLinks) {
222 return FluentIterable.from(dstLinks.get(deviceId))
223 .transform(lookupLink())
224 .filter(notNull())
225 .toSet();
226 }
227 }
228
229 @Override
230 public Link getLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700231 return links.get(linkKey(src, dst));
Madan Jampani2ff05592014-10-10 15:42:47 -0700232 }
233
234 @Override
235 public Set<Link> getEgressLinks(ConnectPoint src) {
236 Set<Link> egress = new HashSet<>();
237 for (LinkKey linkKey : srcLinks.get(src.deviceId())) {
238 if (linkKey.src().equals(src)) {
239 egress.add(links.get(linkKey));
240 }
241 }
242 return egress;
243 }
244
245 @Override
246 public Set<Link> getIngressLinks(ConnectPoint dst) {
247 Set<Link> ingress = new HashSet<>();
248 for (LinkKey linkKey : dstLinks.get(dst.deviceId())) {
249 if (linkKey.dst().equals(dst)) {
250 ingress.add(links.get(linkKey));
251 }
252 }
253 return ingress;
254 }
255
256 @Override
257 public LinkEvent createOrUpdateLink(ProviderId providerId,
258 LinkDescription linkDescription) {
259
260 DeviceId dstDeviceId = linkDescription.dst().deviceId();
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700261 Timestamp newTimestamp = deviceClockService.getTimestamp(dstDeviceId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700262
263 final Timestamped<LinkDescription> deltaDesc = new Timestamped<>(linkDescription, newTimestamp);
264
Yuta HIGUCHI990aecc2014-10-13 22:21:42 -0700265 LinkKey key = linkKey(linkDescription.src(), linkDescription.dst());
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700266 final LinkEvent event;
267 final Timestamped<LinkDescription> mergedDesc;
alshabibdfc7afb2014-10-21 20:13:27 -0700268 Map<ProviderId, Timestamped<LinkDescription>> map = getOrCreateLinkDescriptions(key);
269 synchronized (map) {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700270 event = createOrUpdateLinkInternal(providerId, deltaDesc);
alshabibdfc7afb2014-10-21 20:13:27 -0700271 mergedDesc = map.get(providerId);
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700272 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700273
274 if (event != null) {
275 log.info("Notifying peers of a link update topology event from providerId: "
276 + "{} between src: {} and dst: {}",
277 providerId, linkDescription.src(), linkDescription.dst());
278 try {
Yuta HIGUCHI92cd51e2014-10-13 10:51:45 -0700279 notifyPeers(new InternalLinkEvent(providerId, mergedDesc));
Madan Jampani2ff05592014-10-10 15:42:47 -0700280 } catch (IOException e) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800281 log.debug("Failed to notify peers of a link update topology event from providerId: "
alshabibdfc7afb2014-10-21 20:13:27 -0700282 + "{} between src: {} and dst: {}",
283 providerId, linkDescription.src(), linkDescription.dst());
Madan Jampani2ff05592014-10-10 15:42:47 -0700284 }
285 }
286 return event;
287 }
288
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800289 @Override
290 public LinkEvent removeOrDownLink(ConnectPoint src, ConnectPoint dst) {
291 Link link = getLink(src, dst);
292 if (link == null) {
293 return null;
294 }
295
296 if (link.isDurable()) {
297 // FIXME: this is not the right thing to call for the gossip store; will not sync link state!!!
298 return link.state() == INACTIVE ? null :
299 updateLink(linkKey(link.src(), link.dst()), link,
300 new DefaultLink(link.providerId(),
301 link.src(), link.dst(),
302 link.type(), INACTIVE,
303 link.isDurable(),
304 link.annotations()));
305 }
306 return removeLink(src, dst);
307 }
308
Madan Jampani2ff05592014-10-10 15:42:47 -0700309 private LinkEvent createOrUpdateLinkInternal(
310 ProviderId providerId,
311 Timestamped<LinkDescription> linkDescription) {
312
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700313 final LinkKey key = linkKey(linkDescription.value().src(),
314 linkDescription.value().dst());
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700315 Map<ProviderId, Timestamped<LinkDescription>> descs = getOrCreateLinkDescriptions(key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700316
317 synchronized (descs) {
318 // if the link was previously removed, we should proceed if and
319 // only if this request is more recent.
320 Timestamp linkRemovedTimestamp = removedLinks.get(key);
321 if (linkRemovedTimestamp != null) {
322 if (linkDescription.isNewer(linkRemovedTimestamp)) {
323 removedLinks.remove(key);
324 } else {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700325 log.trace("Link {} was already removed ignoring.", key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700326 return null;
327 }
328 }
329
330 final Link oldLink = links.get(key);
331 // update description
332 createOrUpdateLinkDescription(descs, providerId, linkDescription);
333 final Link newLink = composeLink(descs);
334 if (oldLink == null) {
335 return createLink(key, newLink);
336 }
337 return updateLink(key, oldLink, newLink);
338 }
339 }
340
341 // Guarded by linkDescs value (=locking each Link)
342 private Timestamped<LinkDescription> createOrUpdateLinkDescription(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700343 Map<ProviderId, Timestamped<LinkDescription>> descs,
Madan Jampani2ff05592014-10-10 15:42:47 -0700344 ProviderId providerId,
345 Timestamped<LinkDescription> linkDescription) {
346
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700347 // merge existing annotations
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700348 Timestamped<LinkDescription> existingLinkDescription = descs.get(providerId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700349 if (existingLinkDescription != null && existingLinkDescription.isNewer(linkDescription)) {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700350 log.trace("local info is more up-to-date, ignoring {}.", linkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700351 return null;
352 }
353 Timestamped<LinkDescription> newLinkDescription = linkDescription;
354 if (existingLinkDescription != null) {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700355 // we only allow transition from INDIRECT -> DIRECT
356 final Type newType;
357 if (existingLinkDescription.value().type() == DIRECT) {
358 newType = DIRECT;
359 } else {
360 newType = linkDescription.value().type();
361 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700362 SparseAnnotations merged = union(existingLinkDescription.value().annotations(),
363 linkDescription.value().annotations());
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800364 newLinkDescription = new Timestamped<>(
Madan Jampani2ff05592014-10-10 15:42:47 -0700365 new DefaultLinkDescription(
366 linkDescription.value().src(),
367 linkDescription.value().dst(),
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700368 newType, merged),
Madan Jampani2ff05592014-10-10 15:42:47 -0700369 linkDescription.timestamp());
370 }
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700371 return descs.put(providerId, newLinkDescription);
Madan Jampani2ff05592014-10-10 15:42:47 -0700372 }
373
374 // Creates and stores the link and returns the appropriate event.
375 // Guarded by linkDescs value (=locking each Link)
376 private LinkEvent createLink(LinkKey key, Link newLink) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700377 links.put(key, newLink);
378 srcLinks.put(newLink.src().deviceId(), key);
379 dstLinks.put(newLink.dst().deviceId(), key);
380 return new LinkEvent(LINK_ADDED, newLink);
381 }
382
383 // Updates, if necessary the specified link and returns the appropriate event.
384 // Guarded by linkDescs value (=locking each Link)
385 private LinkEvent updateLink(LinkKey key, Link oldLink, Link newLink) {
Yuta HIGUCHIa85542b2014-10-21 19:29:49 -0700386 // Note: INDIRECT -> DIRECT transition only
387 // so that BDDP discovered Link will not overwrite LDDP Link
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800388 if (oldLink.state() != newLink.state() ||
389 (oldLink.type() == INDIRECT && newLink.type() == DIRECT) ||
Madan Jampani2ff05592014-10-10 15:42:47 -0700390 !AnnotationsUtil.isEqual(oldLink.annotations(), newLink.annotations())) {
391
392 links.put(key, newLink);
393 // strictly speaking following can be ommitted
394 srcLinks.put(oldLink.src().deviceId(), key);
395 dstLinks.put(oldLink.dst().deviceId(), key);
396 return new LinkEvent(LINK_UPDATED, newLink);
397 }
398 return null;
399 }
400
401 @Override
402 public LinkEvent removeLink(ConnectPoint src, ConnectPoint dst) {
Yuta HIGUCHI18ab8a92014-10-13 11:16:19 -0700403 final LinkKey key = linkKey(src, dst);
Madan Jampani2ff05592014-10-10 15:42:47 -0700404
405 DeviceId dstDeviceId = dst.deviceId();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700406 Timestamp timestamp = null;
407 try {
408 timestamp = deviceClockService.getTimestamp(dstDeviceId);
409 } catch (IllegalStateException e) {
Yuta HIGUCHId6a0ac32014-11-04 09:26:31 -0800410 log.warn("Failed to remove link {}, was not the master", key);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700411 //there are times when this is called before mastership
412 // handoff correctly completes.
413 return null;
414 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700415
416 LinkEvent event = removeLinkInternal(key, timestamp);
417
418 if (event != null) {
419 log.info("Notifying peers of a link removed topology event for a link "
420 + "between src: {} and dst: {}", src, dst);
421 try {
422 notifyPeers(new InternalLinkRemovedEvent(key, timestamp));
423 } catch (IOException e) {
424 log.error("Failed to notify peers of a link removed topology event for a link "
425 + "between src: {} and dst: {}", src, dst);
426 }
427 }
428 return event;
429 }
430
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700431 private static Timestamped<LinkDescription> getPrimaryDescription(
432 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
433
Madan Jampani2ff05592014-10-10 15:42:47 -0700434 synchronized (linkDescriptions) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700435 for (Entry<ProviderId, Timestamped<LinkDescription>>
436 e : linkDescriptions.entrySet()) {
437
438 if (!e.getKey().isAncillary()) {
439 return e.getValue();
440 }
441 }
442 }
443 return null;
444 }
445
446
447 // TODO: consider slicing out as Timestamp utils
448 /**
449 * Checks is timestamp is more recent than timestamped object.
450 *
451 * @param timestamp to check if this is more recent then other
452 * @param timestamped object to be tested against
453 * @return true if {@code timestamp} is more recent than {@code timestamped}
454 * or {@code timestamped is null}
455 */
456 private static boolean isMoreRecent(Timestamp timestamp, Timestamped<?> timestamped) {
457 checkNotNull(timestamp);
458 if (timestamped == null) {
459 return true;
460 }
461 return timestamp.compareTo(timestamped.timestamp()) > 0;
462 }
463
464 private LinkEvent removeLinkInternal(LinkKey key, Timestamp timestamp) {
465 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions
466 = getOrCreateLinkDescriptions(key);
467
468 synchronized (linkDescriptions) {
469 if (linkDescriptions.isEmpty()) {
470 // never seen such link before. keeping timestamp for record
471 removedLinks.put(key, timestamp);
472 return null;
473 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700474 // accept removal request if given timestamp is newer than
475 // the latest Timestamp from Primary provider
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700476 Timestamped<LinkDescription> prim = getPrimaryDescription(linkDescriptions);
477 if (!isMoreRecent(timestamp, prim)) {
478 // outdated remove request, ignore
Madan Jampani2ff05592014-10-10 15:42:47 -0700479 return null;
480 }
481 removedLinks.put(key, timestamp);
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800482 Link link = links.remove(key);
Madan Jampani2ff05592014-10-10 15:42:47 -0700483 linkDescriptions.clear();
484 if (link != null) {
485 srcLinks.remove(link.src().deviceId(), key);
486 dstLinks.remove(link.dst().deviceId(), key);
487 return new LinkEvent(LINK_REMOVED, link);
488 }
489 return null;
490 }
491 }
492
493 private static <K, V> SetMultimap<K, V> createSynchronizedHashMultiMap() {
494 return synchronizedSetMultimap(HashMultimap.<K, V>create());
495 }
496
497 /**
498 * @return primary ProviderID, or randomly chosen one if none exists
499 */
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700500 private static ProviderId pickBaseProviderId(
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700501 Map<ProviderId, Timestamped<LinkDescription>> linkDescriptions) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700502
503 ProviderId fallBackPrimary = null;
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700504 for (Entry<ProviderId, Timestamped<LinkDescription>> e : linkDescriptions.entrySet()) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700505 if (!e.getKey().isAncillary()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700506 // found primary
Madan Jampani2ff05592014-10-10 15:42:47 -0700507 return e.getKey();
508 } else if (fallBackPrimary == null) {
509 // pick randomly as a fallback in case there is no primary
510 fallBackPrimary = e.getKey();
511 }
512 }
513 return fallBackPrimary;
514 }
515
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700516 // Guarded by linkDescs value (=locking each Link)
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700517 private Link composeLink(Map<ProviderId, Timestamped<LinkDescription>> descs) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700518 ProviderId baseProviderId = pickBaseProviderId(descs);
519 Timestamped<LinkDescription> base = descs.get(baseProviderId);
Madan Jampani2ff05592014-10-10 15:42:47 -0700520
521 ConnectPoint src = base.value().src();
522 ConnectPoint dst = base.value().dst();
523 Type type = base.value().type();
524 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
525 annotations = merge(annotations, base.value().annotations());
526
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700527 for (Entry<ProviderId, Timestamped<LinkDescription>> e : descs.entrySet()) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700528 if (baseProviderId.equals(e.getKey())) {
Madan Jampani2ff05592014-10-10 15:42:47 -0700529 continue;
530 }
531
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800532 // Note: In the long run we should keep track of Description timestamp
Madan Jampani2ff05592014-10-10 15:42:47 -0700533 // and only merge conflicting keys when timestamp is newer
534 // Currently assuming there will never be a key conflict between
535 // providers
536
537 // annotation merging. not so efficient, should revisit later
538 annotations = merge(annotations, e.getValue().value().annotations());
539 }
540
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800541 boolean isDurable = Objects.equals(annotations.value(AnnotationKeys.DURABLE), "true");
Thomas Vachuskabadb93f2014-11-15 23:51:17 -0800542 return new DefaultLink(baseProviderId, src, dst, type, ACTIVE, isDurable, annotations);
Madan Jampani2ff05592014-10-10 15:42:47 -0700543 }
544
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700545 private Map<ProviderId, Timestamped<LinkDescription>> getOrCreateLinkDescriptions(LinkKey key) {
Yuta HIGUCHI3e1a5bf2014-10-14 19:39:58 -0700546 Map<ProviderId, Timestamped<LinkDescription>> r;
547 r = linkDescs.get(key);
548 if (r != null) {
549 return r;
550 }
551 r = new HashMap<>();
552 final Map<ProviderId, Timestamped<LinkDescription>> concurrentlyAdded;
553 concurrentlyAdded = linkDescs.putIfAbsent(key, r);
554 if (concurrentlyAdded != null) {
555 return concurrentlyAdded;
556 } else {
557 return r;
558 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700559 }
560
561 private final Function<LinkKey, Link> lookupLink = new LookupLink();
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800562
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700563 /**
564 * Returns a Function to lookup Link instance using LinkKey from cache.
Thomas Vachuska57126fe2014-11-11 17:13:24 -0800565 *
566 * @return lookup link function
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700567 */
Madan Jampani2ff05592014-10-10 15:42:47 -0700568 private Function<LinkKey, Link> lookupLink() {
569 return lookupLink;
570 }
571
572 private final class LookupLink implements Function<LinkKey, Link> {
573 @Override
574 public Link apply(LinkKey input) {
Yuta HIGUCHI023295a2014-10-15 23:29:46 -0700575 if (input == null) {
576 return null;
577 } else {
578 return links.get(input);
579 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700580 }
581 }
582
Madan Jampani2ff05592014-10-10 15:42:47 -0700583 private void notifyDelegateIfNotNull(LinkEvent event) {
584 if (event != null) {
585 notifyDelegate(event);
586 }
587 }
588
Madan Jampani2ff05592014-10-10 15:42:47 -0700589 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
590 ClusterMessage message = new ClusterMessage(
591 clusterService.getLocalNode().id(),
592 subject,
593 SERIALIZER.encode(event));
594 clusterCommunicator.broadcast(message);
595 }
596
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700597 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
598 ClusterMessage message = new ClusterMessage(
599 clusterService.getLocalNode().id(),
600 subject,
601 SERIALIZER.encode(event));
602 clusterCommunicator.unicast(message, recipient);
Madan Jampania97e8202014-10-10 17:01:33 -0700603 }
604
Madan Jampani2ff05592014-10-10 15:42:47 -0700605 private void notifyPeers(InternalLinkEvent event) throws IOException {
606 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
607 }
608
609 private void notifyPeers(InternalLinkRemovedEvent event) throws IOException {
610 broadcastMessage(GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
611 }
612
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700613 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700614 private void notifyPeer(NodeId peer, InternalLinkEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700615 try {
616 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_UPDATE, event);
617 } catch (IOException e) {
618 log.debug("Failed to notify peer {} with message {}", peer, event);
619 }
Madan Jampania97e8202014-10-10 17:01:33 -0700620 }
621
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700622 // notify peer, silently ignoring error
Madan Jampania97e8202014-10-10 17:01:33 -0700623 private void notifyPeer(NodeId peer, InternalLinkRemovedEvent event) {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700624 try {
625 unicastMessage(peer, GossipLinkStoreMessageSubjects.LINK_REMOVED, event);
626 } catch (IOException e) {
627 log.debug("Failed to notify peer {} with message {}", peer, event);
628 }
Madan Jampania97e8202014-10-10 17:01:33 -0700629 }
630
631 private final class SendAdvertisementTask implements Runnable {
632
633 @Override
634 public void run() {
635 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800636 log.debug("Interrupted, quitting");
Madan Jampania97e8202014-10-10 17:01:33 -0700637 return;
638 }
639
640 try {
641 final NodeId self = clusterService.getLocalNode().id();
642 Set<ControllerNode> nodes = clusterService.getNodes();
643
644 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
645 .transform(toNodeId())
646 .toList();
647
648 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800649 log.trace("No other peers in the cluster.");
Madan Jampania97e8202014-10-10 17:01:33 -0700650 return;
651 }
652
653 NodeId peer;
654 do {
655 int idx = RandomUtils.nextInt(0, nodeIds.size());
656 peer = nodeIds.get(idx);
657 } while (peer.equals(self));
658
659 LinkAntiEntropyAdvertisement ad = createAdvertisement();
660
661 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800662 log.debug("Interrupted, quitting");
Madan Jampania97e8202014-10-10 17:01:33 -0700663 return;
664 }
665
666 try {
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700667 unicastMessage(peer, LINK_ANTI_ENTROPY_ADVERTISEMENT, ad);
668 } catch (IOException e) {
669 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Madan Jampania97e8202014-10-10 17:01:33 -0700670 return;
671 }
672 } catch (Exception e) {
673 // catch all Exception to avoid Scheduled task being suppressed.
674 log.error("Exception thrown while sending advertisement", e);
675 }
676 }
677 }
678
679 private LinkAntiEntropyAdvertisement createAdvertisement() {
680 final NodeId self = clusterService.getLocalNode().id();
681
682 Map<LinkFragmentId, Timestamp> linkTimestamps = new HashMap<>(linkDescs.size());
683 Map<LinkKey, Timestamp> linkTombstones = new HashMap<>(removedLinks.size());
684
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -0800685 linkDescs.forEach((linkKey, linkDesc) -> {
Madan Jampania97e8202014-10-10 17:01:33 -0700686 synchronized (linkDesc) {
687 for (Map.Entry<ProviderId, Timestamped<LinkDescription>> e : linkDesc.entrySet()) {
688 linkTimestamps.put(new LinkFragmentId(linkKey, e.getKey()), e.getValue().timestamp());
689 }
690 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -0800691 });
Madan Jampania97e8202014-10-10 17:01:33 -0700692
693 linkTombstones.putAll(removedLinks);
694
695 return new LinkAntiEntropyAdvertisement(self, linkTimestamps, linkTombstones);
696 }
697
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700698 private void handleAntiEntropyAdvertisement(LinkAntiEntropyAdvertisement ad) {
Madan Jampania97e8202014-10-10 17:01:33 -0700699
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700700 final NodeId sender = ad.sender();
701 boolean localOutdated = false;
Madan Jampania97e8202014-10-10 17:01:33 -0700702
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700703 for (Entry<LinkKey, Map<ProviderId, Timestamped<LinkDescription>>>
704 l : linkDescs.entrySet()) {
Madan Jampania97e8202014-10-10 17:01:33 -0700705
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700706 final LinkKey key = l.getKey();
707 final Map<ProviderId, Timestamped<LinkDescription>> link = l.getValue();
708 synchronized (link) {
709 Timestamp localLatest = removedLinks.get(key);
Madan Jampania97e8202014-10-10 17:01:33 -0700710
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700711 for (Entry<ProviderId, Timestamped<LinkDescription>> p : link.entrySet()) {
712 final ProviderId providerId = p.getKey();
713 final Timestamped<LinkDescription> pDesc = p.getValue();
Madan Jampania97e8202014-10-10 17:01:33 -0700714
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700715 final LinkFragmentId fragId = new LinkFragmentId(key, providerId);
716 // remote
717 Timestamp remoteTimestamp = ad.linkTimestamps().get(fragId);
718 if (remoteTimestamp == null) {
719 remoteTimestamp = ad.linkTombstones().get(key);
720 }
721 if (remoteTimestamp == null ||
722 pDesc.isNewer(remoteTimestamp)) {
723 // I have more recent link description. update peer.
724 notifyPeer(sender, new InternalLinkEvent(providerId, pDesc));
725 } else {
726 final Timestamp remoteLive = ad.linkTimestamps().get(fragId);
727 if (remoteLive != null &&
728 remoteLive.compareTo(pDesc.timestamp()) > 0) {
729 // I have something outdated
730 localOutdated = true;
731 }
732 }
733
734 // search local latest along the way
735 if (localLatest == null ||
736 pDesc.isNewer(localLatest)) {
737 localLatest = pDesc.timestamp();
738 }
739 }
740 // Tests if remote remove is more recent then local latest.
741 final Timestamp remoteRemove = ad.linkTombstones().get(key);
742 if (remoteRemove != null) {
743 if (localLatest != null &&
744 localLatest.compareTo(remoteRemove) < 0) {
745 // remote remove is more recent
746 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
747 }
748 }
Madan Jampania97e8202014-10-10 17:01:33 -0700749 }
750 }
751
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700752 // populate remove info if not known locally
753 for (Entry<LinkKey, Timestamp> remoteRm : ad.linkTombstones().entrySet()) {
754 final LinkKey key = remoteRm.getKey();
755 final Timestamp remoteRemove = remoteRm.getValue();
756 // relying on removeLinkInternal to ignore stale info
757 notifyDelegateIfNotNull(removeLinkInternal(key, remoteRemove));
758 }
Madan Jampania97e8202014-10-10 17:01:33 -0700759
Yuta HIGUCHI2fe46a22014-10-15 22:51:02 -0700760 if (localOutdated) {
761 // send back advertisement to speed up convergence
762 try {
763 unicastMessage(sender, LINK_ANTI_ENTROPY_ADVERTISEMENT,
764 createAdvertisement());
765 } catch (IOException e) {
766 log.debug("Failed to send back active advertisement");
Madan Jampania97e8202014-10-10 17:01:33 -0700767 }
768 }
769 }
770
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800771 private final class InternalLinkEventListener
772 implements ClusterMessageHandler {
Madan Jampani2ff05592014-10-10 15:42:47 -0700773 @Override
774 public void handle(ClusterMessage message) {
775
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700776 log.trace("Received link event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700777 InternalLinkEvent event = (InternalLinkEvent) SERIALIZER.decode(message.payload());
778
779 ProviderId providerId = event.providerId();
780 Timestamped<LinkDescription> linkDescription = event.linkDescription();
781
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800782 executor.submit(new Runnable() {
783
784 @Override
785 public void run() {
786 try {
787 notifyDelegateIfNotNull(createOrUpdateLinkInternal(providerId, linkDescription));
788 } catch (Exception e) {
789 log.warn("Exception thrown handling link event", e);
790 }
791 }
792 });
Madan Jampani2ff05592014-10-10 15:42:47 -0700793 }
794 }
795
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800796 private final class InternalLinkRemovedEventListener
797 implements ClusterMessageHandler {
Madan Jampani2ff05592014-10-10 15:42:47 -0700798 @Override
799 public void handle(ClusterMessage message) {
800
Yuta HIGUCHIc01d2aa2014-10-19 01:19:34 -0700801 log.trace("Received link removed event from peer: {}", message.sender());
Madan Jampani2ff05592014-10-10 15:42:47 -0700802 InternalLinkRemovedEvent event = (InternalLinkRemovedEvent) SERIALIZER.decode(message.payload());
803
804 LinkKey linkKey = event.linkKey();
805 Timestamp timestamp = event.timestamp();
806
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800807 executor.submit(new Runnable() {
808
809 @Override
810 public void run() {
811 try {
812 notifyDelegateIfNotNull(removeLinkInternal(linkKey, timestamp));
813 } catch (Exception e) {
814 log.warn("Exception thrown handling link removed", e);
815 }
816 }
817 });
Madan Jampani2ff05592014-10-10 15:42:47 -0700818 }
819 }
Madan Jampania97e8202014-10-10 17:01:33 -0700820
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800821 private final class InternalLinkAntiEntropyAdvertisementListener
822 implements ClusterMessageHandler {
Madan Jampania97e8202014-10-10 17:01:33 -0700823
824 @Override
825 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800826 log.trace("Received Link Anti-Entropy advertisement from peer: {}", message.sender());
Madan Jampania97e8202014-10-10 17:01:33 -0700827 LinkAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800828 backgroundExecutors.submit(new Runnable() {
829
830 @Override
831 public void run() {
832 try {
833 handleAntiEntropyAdvertisement(advertisement);
834 } catch (Exception e) {
835 log.warn("Exception thrown while handling Link advertisements", e);
836 throw e;
837 }
838 }
839 });
Madan Jampania97e8202014-10-10 17:01:33 -0700840 }
841 }
Madan Jampani2ff05592014-10-10 15:42:47 -0700842}