blob: 4c83a3808cef4933ebb56e123e5257aeaa02e3e7 [file] [log] [blame]
Charles Chanc91c8782016-03-30 17:54:24 -07001/*
Pier Luigi69f774d2018-02-28 12:10:50 +01002 * Copyright 2018-present Open Networking Foundation
Charles Chanc91c8782016-03-30 17:54:24 -07003 *
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 */
16
Pier Luigi69f774d2018-02-28 12:10:50 +010017package org.onosproject.segmentrouting.mcast;
Charles Chanc91c8782016-03-30 17:54:24 -070018
Pier Luigid29ca7c2018-02-28 17:24:03 +010019import com.google.common.cache.Cache;
20import com.google.common.cache.CacheBuilder;
21import com.google.common.cache.RemovalCause;
22import com.google.common.cache.RemovalNotification;
Pier7b657162018-03-27 11:29:42 -070023import com.google.common.collect.ImmutableList;
Charles Chanc91c8782016-03-30 17:54:24 -070024import com.google.common.collect.ImmutableSet;
25import com.google.common.collect.Lists;
Pier Luigi91573e12018-01-23 16:06:38 +010026import com.google.common.collect.Maps;
Charles Chanc91c8782016-03-30 17:54:24 -070027import com.google.common.collect.Sets;
Charles Chanc91c8782016-03-30 17:54:24 -070028import org.onlab.packet.IpAddress;
Charles Chanc91c8782016-03-30 17:54:24 -070029import org.onlab.packet.VlanId;
30import org.onlab.util.KryoNamespace;
31import org.onosproject.core.ApplicationId;
32import org.onosproject.core.CoreService;
Pier1f87aca2018-03-14 16:47:32 -070033import org.onosproject.mcast.api.McastEvent;
34import org.onosproject.mcast.api.McastRoute;
Pier7b657162018-03-27 11:29:42 -070035import org.onosproject.mcast.api.McastRouteData;
Pier1f87aca2018-03-14 16:47:32 -070036import org.onosproject.mcast.api.McastRouteUpdate;
Pier7b657162018-03-27 11:29:42 -070037import org.onosproject.net.HostId;
Charles Chanc91c8782016-03-30 17:54:24 -070038import org.onosproject.net.ConnectPoint;
39import org.onosproject.net.DeviceId;
40import org.onosproject.net.Link;
41import org.onosproject.net.Path;
42import org.onosproject.net.PortNumber;
Charles Chan72779502016-04-23 17:36:10 -070043import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Charles Chanc91c8782016-03-30 17:54:24 -070044import org.onosproject.net.flowobjective.ForwardingObjective;
45import org.onosproject.net.flowobjective.NextObjective;
Charles Chan72779502016-04-23 17:36:10 -070046import org.onosproject.net.flowobjective.ObjectiveContext;
Pier1f87aca2018-03-14 16:47:32 -070047import org.onosproject.net.topology.LinkWeigher;
Pier Luigid8a15162018-02-15 16:33:08 +010048import org.onosproject.net.topology.Topology;
Charles Chanc91c8782016-03-30 17:54:24 -070049import org.onosproject.net.topology.TopologyService;
Pier1f87aca2018-03-14 16:47:32 -070050import org.onosproject.segmentrouting.SRLinkWeigher;
Pier Luigi69f774d2018-02-28 12:10:50 +010051import org.onosproject.segmentrouting.SegmentRoutingManager;
Charles Chan72779502016-04-23 17:36:10 -070052import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chanc91c8782016-03-30 17:54:24 -070053import org.onosproject.store.serializers.KryoNamespaces;
54import org.onosproject.store.service.ConsistentMap;
55import org.onosproject.store.service.Serializer;
Pier Luigi580fd8a2018-01-16 10:47:50 +010056import org.onosproject.store.service.Versioned;
Charles Chanc91c8782016-03-30 17:54:24 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
Pier Luigi35dab3f2018-01-25 16:16:02 +010060import java.time.Instant;
Charles Chanc91c8782016-03-30 17:54:24 -070061import java.util.Collection;
62import java.util.Collections;
Pier Luigi91573e12018-01-23 16:06:38 +010063import java.util.Comparator;
Charles Chanc91c8782016-03-30 17:54:24 -070064import java.util.List;
Charles Chan72779502016-04-23 17:36:10 -070065import java.util.Map;
Pier1f87aca2018-03-14 16:47:32 -070066import java.util.Map.Entry;
Charles Chanc91c8782016-03-30 17:54:24 -070067import java.util.Optional;
68import java.util.Set;
Pier Luigi35dab3f2018-01-25 16:16:02 +010069import java.util.concurrent.ScheduledExecutorService;
70import java.util.concurrent.TimeUnit;
71import java.util.concurrent.locks.Lock;
72import java.util.concurrent.locks.ReentrantLock;
Charles Chan72779502016-04-23 17:36:10 -070073import java.util.stream.Collectors;
74
Pier Luigi35dab3f2018-01-25 16:16:02 +010075import static java.util.concurrent.Executors.newScheduledThreadPool;
76import static org.onlab.util.Tools.groupedThreads;
Pier1f87aca2018-03-14 16:47:32 -070077
Pier7b657162018-03-27 11:29:42 -070078import static org.onosproject.mcast.api.McastEvent.Type.SOURCES_REMOVED;
79import static org.onosproject.mcast.api.McastEvent.Type.SOURCES_ADDED;
80import static org.onosproject.mcast.api.McastEvent.Type.SINKS_REMOVED;
81import static org.onosproject.mcast.api.McastEvent.Type.SINKS_ADDED;
82import static org.onosproject.mcast.api.McastEvent.Type.ROUTE_REMOVED;
Pier979e61a2018-03-07 11:42:50 +010083import static org.onosproject.segmentrouting.mcast.McastRole.EGRESS;
84import static org.onosproject.segmentrouting.mcast.McastRole.INGRESS;
85import static org.onosproject.segmentrouting.mcast.McastRole.TRANSIT;
Charles Chanc91c8782016-03-30 17:54:24 -070086
87/**
Pier Luigi69f774d2018-02-28 12:10:50 +010088 * Handles Multicast related events.
Charles Chanc91c8782016-03-30 17:54:24 -070089 */
Charles Chan1eaf4802016-04-18 13:44:03 -070090public class McastHandler {
Pier7b657162018-03-27 11:29:42 -070091 // Logger instance
Charles Chan1eaf4802016-04-18 13:44:03 -070092 private static final Logger log = LoggerFactory.getLogger(McastHandler.class);
Pier7b657162018-03-27 11:29:42 -070093 // Reference to srManager and most used internal objects
Charles Chanc91c8782016-03-30 17:54:24 -070094 private final SegmentRoutingManager srManager;
Charles Chan82f19972016-05-17 13:13:55 -070095 private final TopologyService topologyService;
Pier7b657162018-03-27 11:29:42 -070096 // Internal store of the Mcast nextobjectives
Charles Chan72779502016-04-23 17:36:10 -070097 private final ConsistentMap<McastStoreKey, NextObjective> mcastNextObjStore;
Pier7b657162018-03-27 11:29:42 -070098 // Internal store of the Mcast roles
Charles Chan72779502016-04-23 17:36:10 -070099 private final ConsistentMap<McastStoreKey, McastRole> mcastRoleStore;
Pier7b657162018-03-27 11:29:42 -0700100 // McastUtils
101 private final McastUtils mcastUtils;
Charles Chan72779502016-04-23 17:36:10 -0700102
Pier Luigid29ca7c2018-02-28 17:24:03 +0100103 // Wait time for the cache
104 private static final int WAIT_TIME_MS = 1000;
Pier7b657162018-03-27 11:29:42 -0700105
106 // Wait time for the removal of the old location
107 private static final int HOST_MOVED_DELAY_MS = 1000;
108
Pier Luigid29ca7c2018-02-28 17:24:03 +0100109 /**
110 * The mcastEventCache is implemented to avoid race condition by giving more time to the
111 * underlying subsystems to process previous calls.
112 */
113 private Cache<McastCacheKey, McastEvent> mcastEventCache = CacheBuilder.newBuilder()
114 .expireAfterWrite(WAIT_TIME_MS, TimeUnit.MILLISECONDS)
115 .removalListener((RemovalNotification<McastCacheKey, McastEvent> notification) -> {
116 // Get group ip, sink and related event
117 IpAddress mcastIp = notification.getKey().mcastIp();
Pier7b657162018-03-27 11:29:42 -0700118 HostId sink = notification.getKey().sinkHost();
Pier Luigid29ca7c2018-02-28 17:24:03 +0100119 McastEvent mcastEvent = notification.getValue();
120 RemovalCause cause = notification.getCause();
121 log.debug("mcastEventCache removal event. group={}, sink={}, mcastEvent={}, cause={}",
122 mcastIp, sink, mcastEvent, cause);
123 // If it expires or it has been replaced, we deque the event
124 switch (notification.getCause()) {
125 case REPLACED:
126 case EXPIRED:
127 dequeueMcastEvent(mcastEvent);
128 break;
129 default:
130 break;
131 }
132 }).build();
133
134 private void enqueueMcastEvent(McastEvent mcastEvent) {
Pier7b657162018-03-27 11:29:42 -0700135 // Retrieve, currentData, prevData and the group
Pier1f87aca2018-03-14 16:47:32 -0700136 final McastRouteUpdate mcastRouteUpdate = mcastEvent.subject();
Pier7b657162018-03-27 11:29:42 -0700137 final McastRouteUpdate mcastRoutePrevUpdate = mcastEvent.prevSubject();
138 final IpAddress group = mcastRoutePrevUpdate.route().group();
Pier Luigid29ca7c2018-02-28 17:24:03 +0100139 // Let's create the keys of the cache
Pier7b657162018-03-27 11:29:42 -0700140 ImmutableSet.Builder<HostId> sinksBuilder = ImmutableSet.builder();
Pier1f87aca2018-03-14 16:47:32 -0700141 if (mcastEvent.type() == SOURCES_ADDED ||
142 mcastEvent.type() == SOURCES_REMOVED) {
143 // FIXME To be addressed with multiple sources support
Pier7b657162018-03-27 11:29:42 -0700144 sinksBuilder.addAll(Collections.emptySet());
145 } else if (mcastEvent.type() == SINKS_ADDED) {
146 // We need to process the host id one by one
147 mcastRouteUpdate.sinks().forEach(((hostId, connectPoints) -> {
148 // Get the previous locations and verify if there are changes
149 Set<ConnectPoint> prevConnectPoints = mcastRoutePrevUpdate.sinks().get(hostId);
150 Set<ConnectPoint> changes = Sets.difference(connectPoints, prevConnectPoints != null ?
151 prevConnectPoints : Collections.emptySet());
152 if (!changes.isEmpty()) {
153 sinksBuilder.add(hostId);
Pier1f87aca2018-03-14 16:47:32 -0700154 }
Pier7b657162018-03-27 11:29:42 -0700155 }));
156 } else if (mcastEvent.type() == SINKS_REMOVED) {
157 // We need to process the host id one by one
158 mcastRoutePrevUpdate.sinks().forEach(((hostId, connectPoints) -> {
159 // Get the current locations and verify if there are changes
160 Set<ConnectPoint> currentConnectPoints = mcastRouteUpdate.sinks().get(hostId);
161 Set<ConnectPoint> changes = Sets.difference(connectPoints, currentConnectPoints != null ?
162 currentConnectPoints : Collections.emptySet());
163 if (!changes.isEmpty()) {
164 sinksBuilder.add(hostId);
165 }
166 }));
167 } else if (mcastEvent.type() == ROUTE_REMOVED) {
168 // Current subject is null, just take the previous host ids
169 sinksBuilder.addAll(mcastRoutePrevUpdate.sinks().keySet());
Pier Luigid29ca7c2018-02-28 17:24:03 +0100170 }
171 // Push the elements in the cache
172 sinksBuilder.build().forEach(sink -> {
Pier1f87aca2018-03-14 16:47:32 -0700173 McastCacheKey cacheKey = new McastCacheKey(group, sink);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100174 mcastEventCache.put(cacheKey, mcastEvent);
175 });
176 }
177
178 private void dequeueMcastEvent(McastEvent mcastEvent) {
Pier7b657162018-03-27 11:29:42 -0700179 // Get new and old data
180 final McastRouteUpdate mcastUpdate = mcastEvent.subject();
181 final McastRouteUpdate mcastPrevUpdate = mcastEvent.prevSubject();
Pier Luigid29ca7c2018-02-28 17:24:03 +0100182 // Get source, mcast group
Pier1f87aca2018-03-14 16:47:32 -0700183 // FIXME To be addressed with multiple sources support
Pier7b657162018-03-27 11:29:42 -0700184 final ConnectPoint source = mcastPrevUpdate.sources()
Pier1f87aca2018-03-14 16:47:32 -0700185 .stream()
186 .findFirst()
187 .orElse(null);
Pier7b657162018-03-27 11:29:42 -0700188 IpAddress mcastIp = mcastPrevUpdate.route().group();
189 // Get all the previous sinks
190 Set<ConnectPoint> prevSinks = mcastPrevUpdate.sinks()
Pier1f87aca2018-03-14 16:47:32 -0700191 .values()
192 .stream()
193 .flatMap(Collection::stream)
194 .collect(Collectors.toSet());
Pier Luigid29ca7c2018-02-28 17:24:03 +0100195 // According to the event type let's call the proper method
196 switch (mcastEvent.type()) {
Pier1f87aca2018-03-14 16:47:32 -0700197 case SOURCES_ADDED:
198 // FIXME To be addressed with multiple sources support
199 // Get all the sinks
200 //Set<ConnectPoint> sinks = mcastRouteInfo.sinks();
201 // Compute the Mcast tree
202 //Map<ConnectPoint, List<Path>> mcasTree = computeSinkMcastTree(source.deviceId(), sinks);
203 // Process the given sinks using the pre-computed paths
204 //mcasTree.forEach((sink, paths) -> processSinkAddedInternal(source, sink, mcastIp, paths));
Pier Luigid29ca7c2018-02-28 17:24:03 +0100205 break;
Pier1f87aca2018-03-14 16:47:32 -0700206 case SOURCES_REMOVED:
207 // FIXME To be addressed with multiple sources support
Pier Luigid29ca7c2018-02-28 17:24:03 +0100208 // Get old source
Pier1f87aca2018-03-14 16:47:32 -0700209 //ConnectPoint oldSource = mcastEvent.prevSubject().source().orElse(null);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100210 // Just the first cached element will be processed
Pier1f87aca2018-03-14 16:47:32 -0700211 //processSourceUpdatedInternal(mcastIp, source, oldSource);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100212 break;
213 case ROUTE_REMOVED:
214 // Process the route removed, just the first cached element will be processed
Pier7b657162018-03-27 11:29:42 -0700215 processRouteRemovedInternal(source, mcastIp);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100216 break;
Pier1f87aca2018-03-14 16:47:32 -0700217 case SINKS_ADDED:
Pier7b657162018-03-27 11:29:42 -0700218 // FIXME To be addressed with multiple sources support
219 processSinksAddedInternal(source, mcastIp,
220 mcastUpdate.sinks(), prevSinks);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100221 break;
Pier1f87aca2018-03-14 16:47:32 -0700222 case SINKS_REMOVED:
Pier7b657162018-03-27 11:29:42 -0700223 // FIXME To be addressed with multiple sources support
224 processSinksRemovedInternal(source, mcastIp,
225 mcastUpdate.sinks(), prevSinks);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100226 break;
227 default:
228 break;
229 }
230 }
231
Pier Luigi35dab3f2018-01-25 16:16:02 +0100232 // Mcast lock to serialize local operations
233 private final Lock mcastLock = new ReentrantLock();
234
235 /**
236 * Acquires the lock used when making mcast changes.
237 */
238 private void mcastLock() {
239 mcastLock.lock();
240 }
241
242 /**
243 * Releases the lock used when making mcast changes.
244 */
245 private void mcastUnlock() {
246 mcastLock.unlock();
247 }
248
249 // Stability threshold for Mcast. Seconds
250 private static final long MCAST_STABLITY_THRESHOLD = 5;
251 // Last change done
252 private Instant lastMcastChange = Instant.now();
253
254 /**
255 * Determines if mcast in the network has been stable in the last
256 * MCAST_STABLITY_THRESHOLD seconds, by comparing the current time
257 * to the last mcast change timestamp.
258 *
259 * @return true if stable
260 */
261 private boolean isMcastStable() {
262 long last = (long) (lastMcastChange.toEpochMilli() / 1000.0);
263 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das97241862018-02-14 14:14:54 -0800264 log.trace("Mcast stable since {}s", now - last);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100265 return (now - last) > MCAST_STABLITY_THRESHOLD;
266 }
267
268 // Verify interval for Mcast
269 private static final long MCAST_VERIFY_INTERVAL = 30;
270
271 // Executor for mcast bucket corrector
272 private ScheduledExecutorService executorService
Pier Luigid29ca7c2018-02-28 17:24:03 +0100273 = newScheduledThreadPool(1, groupedThreads("mcastWorker", "mcastWorker-%d", log));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100274
Charles Chan72779502016-04-23 17:36:10 -0700275 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700276 * Constructs the McastEventHandler.
277 *
278 * @param srManager Segment Routing manager
279 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700280 public McastHandler(SegmentRoutingManager srManager) {
Pier7b657162018-03-27 11:29:42 -0700281 ApplicationId coreAppId = srManager.coreService.getAppId(CoreService.CORE_APP_NAME);
Charles Chanc91c8782016-03-30 17:54:24 -0700282 this.srManager = srManager;
Charles Chanc91c8782016-03-30 17:54:24 -0700283 this.topologyService = srManager.topologyService;
Pier7b657162018-03-27 11:29:42 -0700284 KryoNamespace.Builder mcastKryo = new KryoNamespace.Builder()
Charles Chanc91c8782016-03-30 17:54:24 -0700285 .register(KryoNamespaces.API)
Charles Chan72779502016-04-23 17:36:10 -0700286 .register(McastStoreKey.class)
287 .register(McastRole.class);
Pier7b657162018-03-27 11:29:42 -0700288 mcastNextObjStore = srManager.storageService
Charles Chan72779502016-04-23 17:36:10 -0700289 .<McastStoreKey, NextObjective>consistentMapBuilder()
Charles Chanc91c8782016-03-30 17:54:24 -0700290 .withName("onos-mcast-nextobj-store")
Charles Chan4922a172016-05-23 16:45:45 -0700291 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-NextObj")))
Charles Chanc91c8782016-03-30 17:54:24 -0700292 .build();
Pier7b657162018-03-27 11:29:42 -0700293 mcastRoleStore = srManager.storageService
Charles Chan72779502016-04-23 17:36:10 -0700294 .<McastStoreKey, McastRole>consistentMapBuilder()
295 .withName("onos-mcast-role-store")
Charles Chan4922a172016-05-23 16:45:45 -0700296 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-Role")))
Charles Chan72779502016-04-23 17:36:10 -0700297 .build();
Pier7b657162018-03-27 11:29:42 -0700298 // Let's create McastUtils object
299 mcastUtils = new McastUtils(srManager, coreAppId, log);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100300 // Init the executor service and the buckets corrector
301 executorService.scheduleWithFixedDelay(new McastBucketCorrector(), 10,
Pier7b657162018-03-27 11:29:42 -0700302 MCAST_VERIFY_INTERVAL, TimeUnit.SECONDS);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100303 // Schedule the clean up, this will allow the processing of the expired events
304 executorService.scheduleAtFixedRate(mcastEventCache::cleanUp, 0,
305 WAIT_TIME_MS, TimeUnit.MILLISECONDS);
Charles Chan72779502016-04-23 17:36:10 -0700306 }
307
308 /**
309 * Read initial multicast from mcast store.
310 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100311 public void init() {
Pier7b657162018-03-27 11:29:42 -0700312 lastMcastChange = Instant.now();
313 mcastLock();
314 try {
315 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
316 // FIXME To be addressed with multiple sources support
317 ConnectPoint source = srManager.multicastRouteService.sources(mcastRoute)
318 .stream()
319 .findFirst()
320 .orElse(null);
321 // Get all the sinks and process them
322 McastRouteData mcastRouteData = srManager.multicastRouteService.routeData(mcastRoute);
323 Set<ConnectPoint> sinks = processSinksToBeAdded(source, mcastRoute.group(), mcastRouteData.sinks());
324 // Filter out all the working sinks, we do not want to move them
325 sinks = sinks.stream()
326 .filter(sink -> {
327 McastStoreKey mcastKey = new McastStoreKey(mcastRoute.group(), sink.deviceId());
328 Versioned<NextObjective> verMcastNext = mcastNextObjStore.get(mcastKey);
329 return verMcastNext == null ||
330 !mcastUtils.getPorts(verMcastNext.value().next()).contains(sink.port());
331 })
332 .collect(Collectors.toSet());
333 // Compute the Mcast tree
334 Map<ConnectPoint, List<Path>> mcasTree = computeSinkMcastTree(source.deviceId(), sinks);
335 // Process the given sinks using the pre-computed paths
336 mcasTree.forEach((sink, paths) -> processSinkAddedInternal(source, sink,
337 mcastRoute.group(), paths));
338 });
339 } finally {
340 mcastUnlock();
341 }
Charles Chanc91c8782016-03-30 17:54:24 -0700342 }
343
344 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100345 * Clean up when deactivating the application.
346 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100347 public void terminate() {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100348 executorService.shutdown();
349 }
350
351 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +0100352 * Processes the SOURCE_ADDED, SOURCE_UPDATED, SINK_ADDED,
353 * SINK_REMOVED and ROUTE_REMOVED events.
Charles Chanc91c8782016-03-30 17:54:24 -0700354 *
355 * @param event McastEvent with SOURCE_ADDED type
356 */
Pier Luigid29ca7c2018-02-28 17:24:03 +0100357 public void processMcastEvent(McastEvent event) {
358 log.info("process {}", event);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100359 // Just enqueue for now
360 enqueueMcastEvent(event);
Pier Luigi6786b922018-02-02 16:19:11 +0100361 }
362
363 /**
Pier Luigie80d6b42018-02-26 12:31:38 +0100364 * Process the SOURCE_UPDATED event.
365 *
366 * @param newSource the updated srouce info
367 * @param oldSource the outdated source info
368 */
369 private void processSourceUpdatedInternal(IpAddress mcastIp,
370 ConnectPoint newSource,
371 ConnectPoint oldSource) {
372 lastMcastChange = Instant.now();
373 mcastLock();
374 try {
375 log.debug("Processing source updated for group {}", mcastIp);
376
377 // Build key for the store and retrieve old data
378 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, oldSource.deviceId());
379
380 // Verify leadership on the operation
Pier7b657162018-03-27 11:29:42 -0700381 if (!mcastUtils.isLeader(oldSource)) {
Pier Luigie80d6b42018-02-26 12:31:38 +0100382 log.debug("Skip {} due to lack of leadership", mcastIp);
383 return;
384 }
385
386 // This device is not serving this multicast group
387 if (!mcastRoleStore.containsKey(mcastStoreKey) ||
388 !mcastNextObjStore.containsKey(mcastStoreKey)) {
389 log.warn("{} is not serving {}. Abort.", oldSource.deviceId(), mcastIp);
390 return;
391 }
392 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
Pier7b657162018-03-27 11:29:42 -0700393 Set<PortNumber> outputPorts = mcastUtils.getPorts(nextObjective.next());
Pier Luigie80d6b42018-02-26 12:31:38 +0100394
Pier Luigid29ca7c2018-02-28 17:24:03 +0100395 // This an optimization to avoid unnecessary removal and add
Pier7b657162018-03-27 11:29:42 -0700396 if (!mcastUtils.assignedVlanFromNext(nextObjective)
397 .equals(mcastUtils.assignedVlan(newSource))) {
Pier Luigid29ca7c2018-02-28 17:24:03 +0100398 // Let's remove old flows and groups
Pier7b657162018-03-27 11:29:42 -0700399 removeGroupFromDevice(oldSource.deviceId(), mcastIp, mcastUtils.assignedVlan(oldSource));
Pier Luigid29ca7c2018-02-28 17:24:03 +0100400 // Push new flows and group
401 outputPorts.forEach(portNumber -> addPortToDevice(newSource.deviceId(), portNumber,
Pier7b657162018-03-27 11:29:42 -0700402 mcastIp, mcastUtils.assignedVlan(newSource)));
Pier Luigid29ca7c2018-02-28 17:24:03 +0100403 }
Pier7b657162018-03-27 11:29:42 -0700404 mcastUtils.addFilterToDevice(newSource.deviceId(), newSource.port(),
405 mcastUtils.assignedVlan(newSource), mcastIp, INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100406 // Setup mcast roles
407 mcastRoleStore.put(new McastStoreKey(mcastIp, newSource.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100408 INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100409 } finally {
410 mcastUnlock();
411 }
412 }
413
414 /**
Pier Luigi6786b922018-02-02 16:19:11 +0100415 * Removes the entire mcast tree related to this group.
416 *
417 * @param mcastIp multicast group IP address
418 */
419 private void processRouteRemovedInternal(ConnectPoint source, IpAddress mcastIp) {
420 lastMcastChange = Instant.now();
421 mcastLock();
422 try {
Pier Luigie80d6b42018-02-26 12:31:38 +0100423 log.debug("Processing route removed for group {}", mcastIp);
Pier Luigi6786b922018-02-02 16:19:11 +0100424
425 // Find out the ingress, transit and egress device of the affected group
Pier979e61a2018-03-07 11:42:50 +0100426 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi6786b922018-02-02 16:19:11 +0100427 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700428 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100429 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi6786b922018-02-02 16:19:11 +0100430
431 // Verify leadership on the operation
Pier7b657162018-03-27 11:29:42 -0700432 if (!mcastUtils.isLeader(source)) {
Pier Luigi6786b922018-02-02 16:19:11 +0100433 log.debug("Skip {} due to lack of leadership", mcastIp);
434 return;
435 }
436
Pier1a7e0c02018-03-12 15:00:54 -0700437 // If there are no egress devices, sinks could be only on the ingress
Pier Luigi6786b922018-02-02 16:19:11 +0100438 if (!egressDevices.isEmpty()) {
439 egressDevices.forEach(
Pier7b657162018-03-27 11:29:42 -0700440 deviceId -> removeGroupFromDevice(deviceId, mcastIp, mcastUtils.assignedVlan(null))
Pier Luigi6786b922018-02-02 16:19:11 +0100441 );
442 }
Pier1a7e0c02018-03-12 15:00:54 -0700443 // Transit could be empty if sinks are on the ingress
444 if (!transitDevices.isEmpty()) {
445 transitDevices.forEach(
Pier7b657162018-03-27 11:29:42 -0700446 deviceId -> removeGroupFromDevice(deviceId, mcastIp, mcastUtils.assignedVlan(null))
Pier1a7e0c02018-03-12 15:00:54 -0700447 );
Pier Luigi6786b922018-02-02 16:19:11 +0100448 }
449 // Ingress device should be not null
450 if (ingressDevice != null) {
Pier7b657162018-03-27 11:29:42 -0700451 removeGroupFromDevice(ingressDevice, mcastIp, mcastUtils.assignedVlan(source));
Pier Luigi6786b922018-02-02 16:19:11 +0100452 }
Pier Luigi6786b922018-02-02 16:19:11 +0100453 } finally {
454 mcastUnlock();
455 }
456 }
457
Pier7b657162018-03-27 11:29:42 -0700458
459 /**
460 * Process sinks to be removed.
461 *
462 * @param source the source connect point
463 * @param mcastIp the ip address of the group
464 * @param newSinks the new sinks to be processed
465 * @param allPrevSinks all previous sinks
466 */
467 private void processSinksRemovedInternal(ConnectPoint source, IpAddress mcastIp,
468 Map<HostId, Set<ConnectPoint>> newSinks,
469 Set<ConnectPoint> allPrevSinks) {
470 lastMcastChange = Instant.now();
471 mcastLock();
472 // Let's instantiate the sinks to be removed
473 Set<ConnectPoint> sinksToBeRemoved = Sets.newHashSet();
474 try {
475 // Recover the dual-homed sinks
476 Set<ConnectPoint> sinksToBeRecovered = processSinksToBeRecovered(mcastIp, newSinks);
477 sinksToBeRecovered.forEach(sink -> processSinkAddedInternal(source, sink, mcastIp, null));
478 // Get the only sinks to be processed (old ones)
479 Set<ConnectPoint> allNewSinks = newSinks.values()
480 .stream()
481 .flatMap(Collection::stream)
482 .collect(Collectors.toSet());
483 // Remove the previous one
484 sinksToBeRemoved.addAll(Sets.difference(allPrevSinks, allNewSinks));
485 } finally {
486 mcastUnlock();
487 // Let's schedule the removal of the previous sinks
488 executorService.schedule(
489 () -> sinksToBeRemoved.forEach(sink -> processSinkRemovedInternal(source, sink, mcastIp)),
490 HOST_MOVED_DELAY_MS, TimeUnit.MILLISECONDS);
491 }
492 }
493
Pier Luigi6786b922018-02-02 16:19:11 +0100494 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100495 * Removes a path from source to sink for given multicast group.
496 *
497 * @param source connect point of the multicast source
498 * @param sink connection point of the multicast sink
499 * @param mcastIp multicast group IP address
500 */
501 private void processSinkRemovedInternal(ConnectPoint source, ConnectPoint sink,
Pier7b657162018-03-27 11:29:42 -0700502 IpAddress mcastIp) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100503 lastMcastChange = Instant.now();
504 mcastLock();
505 try {
Pier Luigi6786b922018-02-02 16:19:11 +0100506 // Verify leadership on the operation
Pier7b657162018-03-27 11:29:42 -0700507 if (!mcastUtils.isLeader(source)) {
Pier Luigi6786b922018-02-02 16:19:11 +0100508 log.debug("Skip {} due to lack of leadership", mcastIp);
Charles Chanc91c8782016-03-30 17:54:24 -0700509 return;
510 }
Charles Chanc91c8782016-03-30 17:54:24 -0700511
Pier7b657162018-03-27 11:29:42 -0700512 boolean isLast;
Pier Luigi35dab3f2018-01-25 16:16:02 +0100513 // When source and sink are on the same device
514 if (source.deviceId().equals(sink.deviceId())) {
515 // Source and sink are on even the same port. There must be something wrong.
516 if (source.port().equals(sink.port())) {
517 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
518 mcastIp, sink, source);
519 return;
520 }
Pier7b657162018-03-27 11:29:42 -0700521 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, mcastUtils.assignedVlan(source));
Pier Luigi92e69be2018-03-02 12:53:37 +0100522 if (isLast) {
523 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
524 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100525 return;
526 }
Charles Chanc91c8782016-03-30 17:54:24 -0700527
Pier Luigi35dab3f2018-01-25 16:16:02 +0100528 // Process the egress device
Pier7b657162018-03-27 11:29:42 -0700529 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, mcastUtils.assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100530 if (isLast) {
531 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
532 }
533
534 // If this is the last sink on the device, also update upstream
Pier1f87aca2018-03-14 16:47:32 -0700535 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(),
536 mcastIp, null);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100537 if (mcastPath.isPresent()) {
538 List<Link> links = Lists.newArrayList(mcastPath.get().links());
539 Collections.reverse(links);
540 for (Link link : links) {
541 if (isLast) {
542 isLast = removePortFromDevice(
543 link.src().deviceId(),
544 link.src().port(),
545 mcastIp,
Pier7b657162018-03-27 11:29:42 -0700546 mcastUtils.assignedVlan(link.src().deviceId().equals(source.deviceId()) ?
547 source : null)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100548 );
Pier Luigi92e69be2018-03-02 12:53:37 +0100549 if (isLast) {
550 mcastRoleStore.remove(new McastStoreKey(mcastIp, link.src().deviceId()));
551 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100552 }
Charles Chanc91c8782016-03-30 17:54:24 -0700553 }
554 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100555 } finally {
556 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700557 }
558 }
559
Pier7b657162018-03-27 11:29:42 -0700560
561 /**
562 * Process sinks to be added.
563 *
564 * @param source the source connect point
565 * @param mcastIp the group IP
566 * @param newSinks the new sinks to be processed
567 * @param allPrevSinks all previous sinks
568 */
569 private void processSinksAddedInternal(ConnectPoint source, IpAddress mcastIp,
570 Map<HostId, Set<ConnectPoint>> newSinks,
571 Set<ConnectPoint> allPrevSinks) {
572 lastMcastChange = Instant.now();
573 mcastLock();
574 try {
575 // Get the only sinks to be processed (new ones)
576 Set<ConnectPoint> sinksToBeAdded = processSinksToBeAdded(source, mcastIp, newSinks);
577 // Install new sinks
578 sinksToBeAdded = Sets.difference(sinksToBeAdded, allPrevSinks);
579 sinksToBeAdded.forEach(sink -> processSinkAddedInternal(source, sink, mcastIp, null));
580 } finally {
581 mcastUnlock();
582 }
583 }
584
Charles Chanc91c8782016-03-30 17:54:24 -0700585 /**
586 * Establishes a path from source to sink for given multicast group.
587 *
588 * @param source connect point of the multicast source
589 * @param sink connection point of the multicast sink
590 * @param mcastIp multicast group IP address
591 */
592 private void processSinkAddedInternal(ConnectPoint source, ConnectPoint sink,
Pier7b657162018-03-27 11:29:42 -0700593 IpAddress mcastIp, List<Path> allPaths) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100594 lastMcastChange = Instant.now();
595 mcastLock();
596 try {
597 // Continue only when this instance is the master of source device
598 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
599 log.debug("Skip {} due to lack of mastership of the source device {}",
600 mcastIp, source.deviceId());
Charles Chanc91c8782016-03-30 17:54:24 -0700601 return;
602 }
Charles Chanc91c8782016-03-30 17:54:24 -0700603
Pier Luigi35dab3f2018-01-25 16:16:02 +0100604 // Process the ingress device
Pier7b657162018-03-27 11:29:42 -0700605 mcastUtils.addFilterToDevice(source.deviceId(), source.port(),
606 mcastUtils.assignedVlan(source), mcastIp, INGRESS);
Charles Chan72779502016-04-23 17:36:10 -0700607
Pier Luigi35dab3f2018-01-25 16:16:02 +0100608 // When source and sink are on the same device
609 if (source.deviceId().equals(sink.deviceId())) {
610 // Source and sink are on even the same port. There must be something wrong.
611 if (source.port().equals(sink.port())) {
612 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
613 mcastIp, sink, source);
614 return;
615 }
Pier7b657162018-03-27 11:29:42 -0700616 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, mcastUtils.assignedVlan(source));
Pier979e61a2018-03-07 11:42:50 +0100617 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()), INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100618 return;
619 }
Charles Chan72779502016-04-23 17:36:10 -0700620
Pier Luigi35dab3f2018-01-25 16:16:02 +0100621 // Find a path. If present, create/update groups and flows for each hop
Pier1f87aca2018-03-14 16:47:32 -0700622 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(),
623 mcastIp, allPaths);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100624 if (mcastPath.isPresent()) {
625 List<Link> links = mcastPath.get().links();
Charles Chan72779502016-04-23 17:36:10 -0700626
Pier1a7e0c02018-03-12 15:00:54 -0700627 // Setup mcast role for ingress
628 mcastRoleStore.put(new McastStoreKey(mcastIp, source.deviceId()),
629 INGRESS);
630
631 // Setup properly the transit
Pier Luigi35dab3f2018-01-25 16:16:02 +0100632 links.forEach(link -> {
633 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
Pier7b657162018-03-27 11:29:42 -0700634 mcastUtils.assignedVlan(link.src().deviceId()
635 .equals(source.deviceId()) ? source : null));
636 mcastUtils.addFilterToDevice(link.dst().deviceId(), link.dst().port(),
637 mcastUtils.assignedVlan(null), mcastIp, null);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100638 });
639
Pier1a7e0c02018-03-12 15:00:54 -0700640 // Setup mcast role for the transit
641 links.stream()
642 .filter(link -> !link.dst().deviceId().equals(sink.deviceId()))
643 .forEach(link -> mcastRoleStore.put(new McastStoreKey(mcastIp, link.dst().deviceId()),
644 TRANSIT));
645
Pier Luigi35dab3f2018-01-25 16:16:02 +0100646 // Process the egress device
Pier7b657162018-03-27 11:29:42 -0700647 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, mcastUtils.assignedVlan(null));
Pier1a7e0c02018-03-12 15:00:54 -0700648 // Setup mcast role for egress
Pier Luigi35dab3f2018-01-25 16:16:02 +0100649 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100650 EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100651 } else {
652 log.warn("Unable to find a path from {} to {}. Abort sinkAdded",
653 source.deviceId(), sink.deviceId());
654 }
655 } finally {
656 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700657 }
658 }
659
660 /**
Charles Chan72779502016-04-23 17:36:10 -0700661 * Processes the LINK_DOWN event.
662 *
663 * @param affectedLink Link that is going down
664 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100665 public void processLinkDown(Link affectedLink) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100666 lastMcastChange = Instant.now();
667 mcastLock();
668 try {
669 // Get groups affected by the link down event
670 getAffectedGroups(affectedLink).forEach(mcastIp -> {
671 // TODO Optimize when the group editing is in place
672 log.debug("Processing link down {} for group {}",
673 affectedLink, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100674
Pier Luigi35dab3f2018-01-25 16:16:02 +0100675 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100676 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100677 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700678 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100679 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier7b657162018-03-27 11:29:42 -0700680 ConnectPoint source = mcastUtils.getSource(mcastIp);
Charles Chana8f9dee2016-05-16 18:44:13 -0700681
Pier1a7e0c02018-03-12 15:00:54 -0700682 // Do not proceed if ingress device or source of this group are missing
683 // If sinks are in other leafs, we have ingress, transit, egress, and source
684 // If sinks are in the same leaf, we have just ingress and source
685 if (ingressDevice == null || source == null) {
686 log.warn("Missing ingress {} or source {} for group {}",
687 ingressDevice, source, mcastIp);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100688 return;
Charles Chan72779502016-04-23 17:36:10 -0700689 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100690
691 // Continue only when this instance is the master of source device
692 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
693 log.debug("Skip {} due to lack of mastership of the source device {}",
Pier1f87aca2018-03-14 16:47:32 -0700694 mcastIp, source.deviceId());
Pier Luigi35dab3f2018-01-25 16:16:02 +0100695 return;
696 }
697
698 // Remove entire transit
Pier1a7e0c02018-03-12 15:00:54 -0700699 transitDevices.forEach(transitDevice ->
Pier7b657162018-03-27 11:29:42 -0700700 removeGroupFromDevice(transitDevice, mcastIp,
701 mcastUtils.assignedVlan(null)));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100702
Pier1a7e0c02018-03-12 15:00:54 -0700703 // Remove transit-facing ports on the ingress device
704 removeIngressTransitPorts(mcastIp, ingressDevice, source);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100705
Pier7b657162018-03-27 11:29:42 -0700706 // TODO create a shared procedure with DEVICE_DOWN
Pier1f87aca2018-03-14 16:47:32 -0700707 // Compute mcast tree for the the egress devices
708 Map<DeviceId, List<Path>> mcastTree = computeMcastTree(ingressDevice, egressDevices);
709
Pier7b657162018-03-27 11:29:42 -0700710 // We have to verify, if there are egresses without paths
711 Set<DeviceId> notRecovered = Sets.newHashSet();
Pier1f87aca2018-03-14 16:47:32 -0700712 mcastTree.forEach((egressDevice, paths) -> {
Pier7b657162018-03-27 11:29:42 -0700713 // Let's check if there is at least a path
Pier1f87aca2018-03-14 16:47:32 -0700714 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice,
715 mcastIp, paths);
Pier7b657162018-03-27 11:29:42 -0700716 // No paths, we have to try with alternative location
717 if (!mcastPath.isPresent()) {
718 notRecovered.add(egressDevice);
719 // We were not able to find an alternative path for this egress
Pier Luigi35dab3f2018-01-25 16:16:02 +0100720 log.warn("Fail to recover egress device {} from link failure {}",
721 egressDevice, affectedLink);
Pier7b657162018-03-27 11:29:42 -0700722 removeGroupFromDevice(egressDevice, mcastIp,
723 mcastUtils.assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100724 }
725 });
Pier7b657162018-03-27 11:29:42 -0700726
727 // Fast path, we can recover all the locations
728 if (notRecovered.isEmpty()) {
729 // Construct a new path for each egress device
730 mcastTree.forEach((egressDevice, paths) -> {
731 // We try to enforce the sinks path on the mcast tree
732 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice,
733 mcastIp, paths);
734 // If a path is present, let's install it
735 if (mcastPath.isPresent()) {
736 installPath(mcastIp, source, mcastPath.get());
737 }
738 });
739 } else {
740 // Let's try to recover using alternate
741 recoverSinks(egressDevices, notRecovered, mcastIp,
742 ingressDevice, source, true);
743 }
Charles Chan72779502016-04-23 17:36:10 -0700744 });
Pier Luigi35dab3f2018-01-25 16:16:02 +0100745 } finally {
746 mcastUnlock();
747 }
Charles Chan72779502016-04-23 17:36:10 -0700748 }
749
750 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +0100751 * Process the DEVICE_DOWN event.
752 *
753 * @param deviceDown device going down
754 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100755 public void processDeviceDown(DeviceId deviceDown) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100756 lastMcastChange = Instant.now();
757 mcastLock();
758 try {
759 // Get the mcast groups affected by the device going down
760 getAffectedGroups(deviceDown).forEach(mcastIp -> {
761 // TODO Optimize when the group editing is in place
762 log.debug("Processing device down {} for group {}",
763 deviceDown, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100764
Pier Luigi35dab3f2018-01-25 16:16:02 +0100765 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100766 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100767 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700768 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100769 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier7b657162018-03-27 11:29:42 -0700770 ConnectPoint source = mcastUtils.getSource(mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100771
Pier Luigi35dab3f2018-01-25 16:16:02 +0100772 // Do not proceed if ingress device or source of this group are missing
773 // If sinks are in other leafs, we have ingress, transit, egress, and source
774 // If sinks are in the same leaf, we have just ingress and source
775 if (ingressDevice == null || source == null) {
776 log.warn("Missing ingress {} or source {} for group {}",
777 ingressDevice, source, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100778 return;
779 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100780
Pier Luigi6786b922018-02-02 16:19:11 +0100781 // Verify leadership on the operation
Pier7b657162018-03-27 11:29:42 -0700782 if (!mcastUtils.isLeader(source)) {
Pier Luigi6786b922018-02-02 16:19:11 +0100783 log.debug("Skip {} due to lack of leadership", mcastIp);
784 return;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100785 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100786
787 // If it exists, we have to remove it in any case
Pier1a7e0c02018-03-12 15:00:54 -0700788 if (!transitDevices.isEmpty()) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100789 // Remove entire transit
Pier1a7e0c02018-03-12 15:00:54 -0700790 transitDevices.forEach(transitDevice ->
Pier7b657162018-03-27 11:29:42 -0700791 removeGroupFromDevice(transitDevice, mcastIp,
792 mcastUtils.assignedVlan(null)));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100793 }
794 // If the ingress is down
795 if (ingressDevice.equals(deviceDown)) {
796 // Remove entire ingress
Pier7b657162018-03-27 11:29:42 -0700797 removeGroupFromDevice(ingressDevice, mcastIp, mcastUtils.assignedVlan(source));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100798 // If other sinks different from the ingress exist
799 if (!egressDevices.isEmpty()) {
800 // Remove all the remaining egress
801 egressDevices.forEach(
Pier7b657162018-03-27 11:29:42 -0700802 egressDevice -> removeGroupFromDevice(egressDevice, mcastIp,
803 mcastUtils.assignedVlan(null))
Pier Luigi35dab3f2018-01-25 16:16:02 +0100804 );
Pier Luigi580fd8a2018-01-16 10:47:50 +0100805 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100806 } else {
807 // Egress or transit could be down at this point
Pier1a7e0c02018-03-12 15:00:54 -0700808 // Get the ingress-transit ports if they exist
809 removeIngressTransitPorts(mcastIp, ingressDevice, source);
810
Pier Luigi35dab3f2018-01-25 16:16:02 +0100811 // One of the egress device is down
812 if (egressDevices.contains(deviceDown)) {
813 // Remove entire device down
Pier7b657162018-03-27 11:29:42 -0700814 removeGroupFromDevice(deviceDown, mcastIp, mcastUtils.assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100815 // Remove the device down from egress
816 egressDevices.remove(deviceDown);
817 // If there are no more egress and ingress does not have sinks
818 if (egressDevices.isEmpty() && !hasSinks(ingressDevice, mcastIp)) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100819 // We have done
820 return;
821 }
822 }
Pier1f87aca2018-03-14 16:47:32 -0700823
824 // Compute mcast tree for the the egress devices
825 Map<DeviceId, List<Path>> mcastTree = computeMcastTree(ingressDevice, egressDevices);
826
Pier7b657162018-03-27 11:29:42 -0700827 // We have to verify, if there are egresses without paths
828 Set<DeviceId> notRecovered = Sets.newHashSet();
Pier1f87aca2018-03-14 16:47:32 -0700829 mcastTree.forEach((egressDevice, paths) -> {
Pier7b657162018-03-27 11:29:42 -0700830 // Let's check if there is at least a path
Pier1f87aca2018-03-14 16:47:32 -0700831 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice,
Pier7b657162018-03-27 11:29:42 -0700832 mcastIp, paths);
833 // No paths, we have to try with alternative location
834 if (!mcastPath.isPresent()) {
835 notRecovered.add(egressDevice);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100836 // We were not able to find an alternative path for this egress
837 log.warn("Fail to recover egress device {} from device down {}",
838 egressDevice, deviceDown);
Pier7b657162018-03-27 11:29:42 -0700839 removeGroupFromDevice(egressDevice, mcastIp, mcastUtils.assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100840 }
841 });
Pier7b657162018-03-27 11:29:42 -0700842
843 // Fast path, we can recover all the locations
844 if (notRecovered.isEmpty()) {
845 // Construct a new path for each egress device
846 mcastTree.forEach((egressDevice, paths) -> {
847 // We try to enforce the sinks path on the mcast tree
848 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice,
849 mcastIp, paths);
850 // If a path is present, let's install it
851 if (mcastPath.isPresent()) {
852 installPath(mcastIp, source, mcastPath.get());
853 }
854 });
855 } else {
856 // Let's try to recover using alternate
857 recoverSinks(egressDevices, notRecovered, mcastIp,
858 ingressDevice, source, false);
859 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100860 }
861 });
862 } finally {
863 mcastUnlock();
864 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100865 }
866
867 /**
Pier7b657162018-03-27 11:29:42 -0700868 * Try to recover sinks using alternate locations.
869 *
870 * @param egressDevices the original egress devices
871 * @param notRecovered the devices not recovered
872 * @param mcastIp the group address
873 * @param ingressDevice the ingress device
874 * @param source the source connect point
875 * @param isLinkFailure true if it is a link failure, otherwise false
876 */
877 private void recoverSinks(Set<DeviceId> egressDevices, Set<DeviceId> notRecovered,
878 IpAddress mcastIp, DeviceId ingressDevice, ConnectPoint source,
879 boolean isLinkFailure) {
880 // Recovered devices
881 Set<DeviceId> recovered = Sets.difference(egressDevices, notRecovered);
882 // Total affected sinks
883 Set<ConnectPoint> totalAffectedSinks = Sets.newHashSet();
884 // Total sinks
885 Set<ConnectPoint> totalSinks = Sets.newHashSet();
886 // Let's compute all the affected sinks and all the sinks
887 notRecovered.forEach(deviceId -> {
888 totalAffectedSinks.addAll(
889 mcastUtils.getAffectedSinks(deviceId, mcastIp)
890 .values()
891 .stream()
892 .flatMap(Collection::stream)
893 .filter(connectPoint -> connectPoint.deviceId().equals(deviceId))
894 .collect(Collectors.toSet())
895 );
896 totalSinks.addAll(
897 mcastUtils.getAffectedSinks(deviceId, mcastIp)
898 .values()
899 .stream()
900 .flatMap(Collection::stream)
901 .collect(Collectors.toSet())
902 );
903 });
904
905 // Sinks to be added
906 Set<ConnectPoint> sinksToBeAdded = Sets.difference(totalSinks, totalAffectedSinks);
907 // New egress devices, filtering out the source
908 Set<DeviceId> newEgressDevice = sinksToBeAdded.stream()
909 .map(ConnectPoint::deviceId)
910 .collect(Collectors.toSet());
911 // Let's add the devices recovered from the previous round
912 newEgressDevice.addAll(recovered);
913 // Let's do a copy of the new egresses and filter out the source
914 Set<DeviceId> copyNewEgressDevice = ImmutableSet.copyOf(newEgressDevice);
915 newEgressDevice = newEgressDevice.stream()
916 .filter(deviceId -> !deviceId.equals(ingressDevice))
917 .collect(Collectors.toSet());
918
919 // Re-compute mcast tree for the the egress devices
920 Map<DeviceId, List<Path>> mcastTree = computeMcastTree(ingressDevice, newEgressDevice);
921 // if the source was originally in the new locations, add new sinks
922 if (copyNewEgressDevice.contains(ingressDevice)) {
923 sinksToBeAdded.stream()
924 .filter(connectPoint -> connectPoint.deviceId().equals(ingressDevice))
925 .forEach(sink -> processSinkAddedInternal(source, sink, mcastIp, ImmutableList.of()));
926 }
927
928 // Construct a new path for each egress device
929 mcastTree.forEach((egressDevice, paths) -> {
930 // We try to enforce the sinks path on the mcast tree
931 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice,
932 mcastIp, paths);
933 // If a path is present, let's install it
934 if (mcastPath.isPresent()) {
935 // Using recovery procedure
936 if (recovered.contains(egressDevice)) {
937 installPath(mcastIp, source, mcastPath.get());
938 } else {
939 // otherwise we need to threat as new sink
940 sinksToBeAdded.stream()
941 .filter(connectPoint -> connectPoint.deviceId().equals(egressDevice))
942 .forEach(sink -> processSinkAddedInternal(source, sink, mcastIp, paths));
943 }
944 } else {
945 // We were not able to find an alternative path for this egress
946 log.warn("Fail to recover egress device {} from {} failure",
947 egressDevice, isLinkFailure ? "Link" : "Device");
948 removeGroupFromDevice(egressDevice, mcastIp, mcastUtils.assignedVlan(null));
949 }
950 });
951
952 }
953
954 /**
955 * Process new locations and return the set of sinks to be added
956 * in the context of the recovery.
957 *
958 * @param sinks the remaining locations
959 * @return the set of the sinks to be processed
960 */
961 private Set<ConnectPoint> processSinksToBeRecovered(IpAddress mcastIp,
962 Map<HostId, Set<ConnectPoint>> sinks) {
963 // Iterate over the sinks in order to build the set
964 // of the connect points to be served by this group
965 final Set<ConnectPoint> sinksToBeProcessed = Sets.newHashSet();
966 sinks.forEach((hostId, connectPoints) -> {
967 // If it has more than 1 locations
968 if (connectPoints.size() > 1 || connectPoints.size() == 0) {
969 log.debug("Skip {} since sink {} has {} locations",
970 mcastIp, hostId, connectPoints.size());
971 return;
972 }
973 sinksToBeProcessed.add(connectPoints.stream()
974 .findFirst().orElseGet(null));
975 });
976 return sinksToBeProcessed;
977 }
978
979 /**
980 * Process all the sinks related to a mcast group and return
981 * the ones to be processed.
982 *
983 * @param source the source connect point
984 * @param mcastIp the group address
985 * @param sinks the sinks to be evaluated
986 * @return the set of the sinks to be processed
987 */
988 private Set<ConnectPoint> processSinksToBeAdded(ConnectPoint source, IpAddress mcastIp,
989 Map<HostId, Set<ConnectPoint>> sinks) {
990 // Iterate over the sinks in order to build the set
991 // of the connect points to be served by this group
992 final Set<ConnectPoint> sinksToBeProcessed = Sets.newHashSet();
993 sinks.forEach(((hostId, connectPoints) -> {
994 // If it has more than 2 locations
995 if (connectPoints.size() > 2 || connectPoints.size() == 0) {
996 log.debug("Skip {} since sink {} has {} locations",
997 mcastIp, hostId, connectPoints.size());
998 return;
999 }
1000 // If it has one location, just use it
1001 if (connectPoints.size() == 1) {
1002 sinksToBeProcessed.add(connectPoints.stream()
1003 .findFirst().orElseGet(null));
1004 return;
1005 }
1006 // We prefer to reuse existing flows
1007 ConnectPoint sinkToBeProcessed = connectPoints.stream()
1008 .filter(connectPoint -> {
1009 // Let's check if we are already serving that location
1010 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, connectPoint.deviceId());
1011 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1012 return false;
1013 }
1014 // Get next and check with the port
1015 NextObjective mcastNext = mcastNextObjStore.get(mcastStoreKey).value();
1016 return mcastUtils.getPorts(mcastNext.next()).contains(connectPoint.port());
1017 })
1018 .findFirst().orElse(null);
1019 if (sinkToBeProcessed != null) {
1020 sinksToBeProcessed.add(sinkToBeProcessed);
1021 return;
1022 }
1023 // Otherwise we prefer to reuse existing egresses
1024 Set<DeviceId> egresses = getDevice(mcastIp, EGRESS);
1025 sinkToBeProcessed = connectPoints.stream()
1026 .filter(egresses::contains)
1027 .findFirst().orElse(null);
1028 if (sinkToBeProcessed != null) {
1029 sinksToBeProcessed.add(sinkToBeProcessed);
1030 return;
1031 }
1032 // Otherwise we prefer a location co-located with the source (if it exists)
1033 sinkToBeProcessed = connectPoints.stream()
1034 .filter(connectPoint -> connectPoint.deviceId().equals(source.deviceId()))
1035 .findFirst().orElse(null);
1036 if (sinkToBeProcessed != null) {
1037 sinksToBeProcessed.add(sinkToBeProcessed);
1038 return;
1039 }
1040 // Finally, we randomly pick a new location
1041 sinksToBeProcessed.add(connectPoints.stream()
1042 .findFirst().orElseGet(null));
1043 }));
1044 // We have done, return the set
1045 return sinksToBeProcessed;
1046 }
1047
1048 /**
Pier1a7e0c02018-03-12 15:00:54 -07001049 * Utility method to remove all the ingress transit ports.
1050 *
1051 * @param mcastIp the group ip
1052 * @param ingressDevice the ingress device for this group
1053 * @param source the source connect point
1054 */
1055 private void removeIngressTransitPorts(IpAddress mcastIp, DeviceId ingressDevice,
1056 ConnectPoint source) {
1057 Set<PortNumber> ingressTransitPorts = ingressTransitPort(mcastIp);
1058 ingressTransitPorts.forEach(ingressTransitPort -> {
1059 if (ingressTransitPort != null) {
1060 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
Pier7b657162018-03-27 11:29:42 -07001061 mcastIp, mcastUtils.assignedVlan(source));
Pier1a7e0c02018-03-12 15:00:54 -07001062 if (isLast) {
1063 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
1064 }
1065 }
1066 });
1067 }
1068
1069 /**
Charles Chanc91c8782016-03-30 17:54:24 -07001070 * Adds a port to given multicast group on given device. This involves the
1071 * update of L3 multicast group and multicast routing table entry.
1072 *
1073 * @param deviceId device ID
1074 * @param port port to be added
1075 * @param mcastIp multicast group
1076 * @param assignedVlan assigned VLAN ID
1077 */
1078 private void addPortToDevice(DeviceId deviceId, PortNumber port,
Pier7b657162018-03-27 11:29:42 -07001079 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -07001080 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -07001081 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Pier Luigi4f0dd212018-01-19 10:24:53 +01001082 NextObjective newNextObj;
Charles Chan72779502016-04-23 17:36:10 -07001083 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -07001084 // First time someone request this mcast group via this device
1085 portBuilder.add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +01001086 // New nextObj
Pier7b657162018-03-27 11:29:42 -07001087 newNextObj = mcastUtils.nextObjBuilder(mcastIp, assignedVlan,
Pier Luigi4f0dd212018-01-19 10:24:53 +01001088 portBuilder.build(), null).add();
1089 // Store the new port
1090 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -07001091 } else {
1092 // This device already serves some subscribers of this mcast group
Charles Chan72779502016-04-23 17:36:10 -07001093 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -07001094 // Stop if the port is already in the nextobj
Pier7b657162018-03-27 11:29:42 -07001095 Set<PortNumber> existingPorts = mcastUtils.getPorts(nextObj.next());
Charles Chanc91c8782016-03-30 17:54:24 -07001096 if (existingPorts.contains(port)) {
1097 log.info("NextObj for {}/{} already exists. Abort", deviceId, port);
1098 return;
1099 }
Pier Luigi4f0dd212018-01-19 10:24:53 +01001100 // Let's add the port and reuse the previous one
Yuta HIGUCHIbef07b52018-02-09 18:05:23 -08001101 portBuilder.addAll(existingPorts).add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +01001102 // Reuse previous nextObj
Pier7b657162018-03-27 11:29:42 -07001103 newNextObj = mcastUtils.nextObjBuilder(mcastIp, assignedVlan,
Pier Luigi4f0dd212018-01-19 10:24:53 +01001104 portBuilder.build(), nextObj.id()).addToExisting();
1105 // Store the final next objective and send only the difference to the driver
1106 mcastNextObjStore.put(mcastStoreKey, newNextObj);
1107 // Add just the new port
1108 portBuilder = ImmutableSet.builder();
1109 portBuilder.add(port);
Pier7b657162018-03-27 11:29:42 -07001110 newNextObj = mcastUtils.nextObjBuilder(mcastIp, assignedVlan,
Pier Luigi4f0dd212018-01-19 10:24:53 +01001111 portBuilder.build(), nextObj.id()).addToExisting();
Charles Chanc91c8782016-03-30 17:54:24 -07001112 }
1113 // Create, store and apply the new nextObj and fwdObj
Charles Chan72779502016-04-23 17:36:10 -07001114 ObjectiveContext context = new DefaultObjectiveContext(
1115 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
1116 mcastIp, deviceId, port.toLong(), assignedVlan),
1117 (objective, error) ->
1118 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
1119 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier7b657162018-03-27 11:29:42 -07001120 ForwardingObjective fwdObj = mcastUtils.fwdObjBuilder(mcastIp, assignedVlan,
1121 newNextObj.id()).add(context);
Charles Chanc91c8782016-03-30 17:54:24 -07001122 srManager.flowObjectiveService.next(deviceId, newNextObj);
1123 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -07001124 }
1125
1126 /**
1127 * Removes a port from given multicast group on given device.
1128 * This involves the update of L3 multicast group and multicast routing
1129 * table entry.
1130 *
1131 * @param deviceId device ID
1132 * @param port port to be added
1133 * @param mcastIp multicast group
1134 * @param assignedVlan assigned VLAN ID
1135 * @return true if this is the last sink on this device
1136 */
1137 private boolean removePortFromDevice(DeviceId deviceId, PortNumber port,
Pier7b657162018-03-27 11:29:42 -07001138 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -07001139 McastStoreKey mcastStoreKey =
1140 new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -07001141 // This device is not serving this multicast group
Charles Chan72779502016-04-23 17:36:10 -07001142 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -07001143 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
1144 return false;
1145 }
Charles Chan72779502016-04-23 17:36:10 -07001146 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -07001147
Pier7b657162018-03-27 11:29:42 -07001148 Set<PortNumber> existingPorts = mcastUtils.getPorts(nextObj.next());
Charles Chan72779502016-04-23 17:36:10 -07001149 // This port does not serve this multicast group
Charles Chanc91c8782016-03-30 17:54:24 -07001150 if (!existingPorts.contains(port)) {
1151 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
1152 return false;
1153 }
1154 // Copy and modify the ImmutableSet
1155 existingPorts = Sets.newHashSet(existingPorts);
1156 existingPorts.remove(port);
1157
1158 NextObjective newNextObj;
Pier Luigi8cd46de2018-01-19 10:24:53 +01001159 ObjectiveContext context;
Charles Chanc91c8782016-03-30 17:54:24 -07001160 ForwardingObjective fwdObj;
1161 if (existingPorts.isEmpty()) {
Pier Luigi8cd46de2018-01-19 10:24:53 +01001162 // If this is the last sink, remove flows and last bucket
Charles Chanc91c8782016-03-30 17:54:24 -07001163 // NOTE: Rely on GroupStore garbage collection rather than explicitly
1164 // remove L3MG since there might be other flows/groups refer to
1165 // the same L2IG
Pier Luigi8cd46de2018-01-19 10:24:53 +01001166 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -07001167 (objective) -> log.debug("Successfully remove {} on {}/{}, vlan {}",
1168 mcastIp, deviceId, port.toLong(), assignedVlan),
1169 (objective, error) ->
1170 log.warn("Failed to remove {} on {}/{}, vlan {}: {}",
1171 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier7b657162018-03-27 11:29:42 -07001172 fwdObj = mcastUtils.fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
Charles Chan72779502016-04-23 17:36:10 -07001173 mcastNextObjStore.remove(mcastStoreKey);
Charles Chanc91c8782016-03-30 17:54:24 -07001174 } else {
1175 // If this is not the last sink, update flows and groups
Pier Luigi8cd46de2018-01-19 10:24:53 +01001176 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -07001177 (objective) -> log.debug("Successfully update {} on {}/{}, vlan {}",
1178 mcastIp, deviceId, port.toLong(), assignedVlan),
1179 (objective, error) ->
1180 log.warn("Failed to update {} on {}/{}, vlan {}: {}",
1181 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier Luigi8cd46de2018-01-19 10:24:53 +01001182 // Here we store the next objective with the remaining port
Pier7b657162018-03-27 11:29:42 -07001183 newNextObj = mcastUtils.nextObjBuilder(mcastIp, assignedVlan,
Pier Luigi8cd46de2018-01-19 10:24:53 +01001184 existingPorts, nextObj.id()).removeFromExisting();
Pier7b657162018-03-27 11:29:42 -07001185 fwdObj = mcastUtils.fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chan72779502016-04-23 17:36:10 -07001186 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -07001187 }
Pier Luigi8cd46de2018-01-19 10:24:53 +01001188 // Let's modify the next objective removing the bucket
Pier7b657162018-03-27 11:29:42 -07001189 newNextObj = mcastUtils.nextObjBuilder(mcastIp, assignedVlan,
Pier Luigi8cd46de2018-01-19 10:24:53 +01001190 ImmutableSet.of(port), nextObj.id()).removeFromExisting();
1191 srManager.flowObjectiveService.next(deviceId, newNextObj);
1192 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -07001193 return existingPorts.isEmpty();
1194 }
1195
Charles Chan72779502016-04-23 17:36:10 -07001196 /**
1197 * Removes entire group on given device.
1198 *
1199 * @param deviceId device ID
1200 * @param mcastIp multicast group to be removed
1201 * @param assignedVlan assigned VLAN ID
1202 */
1203 private void removeGroupFromDevice(DeviceId deviceId, IpAddress mcastIp,
Pier7b657162018-03-27 11:29:42 -07001204 VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -07001205 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
1206 // This device is not serving this multicast group
1207 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1208 log.warn("{} is not serving {}. Abort.", deviceId, mcastIp);
1209 return;
1210 }
1211 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
1212 // NOTE: Rely on GroupStore garbage collection rather than explicitly
1213 // remove L3MG since there might be other flows/groups refer to
1214 // the same L2IG
1215 ObjectiveContext context = new DefaultObjectiveContext(
1216 (objective) -> log.debug("Successfully remove {} on {}, vlan {}",
1217 mcastIp, deviceId, assignedVlan),
1218 (objective, error) ->
1219 log.warn("Failed to remove {} on {}, vlan {}: {}",
1220 mcastIp, deviceId, assignedVlan, error));
Pier7b657162018-03-27 11:29:42 -07001221 ForwardingObjective fwdObj = mcastUtils.fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
Charles Chan72779502016-04-23 17:36:10 -07001222 srManager.flowObjectiveService.forward(deviceId, fwdObj);
1223 mcastNextObjStore.remove(mcastStoreKey);
1224 mcastRoleStore.remove(mcastStoreKey);
1225 }
1226
Pier Luigi580fd8a2018-01-16 10:47:50 +01001227 private void installPath(IpAddress mcastIp, ConnectPoint source, Path mcastPath) {
1228 // Get Links
1229 List<Link> links = mcastPath.links();
Pier1a7e0c02018-03-12 15:00:54 -07001230
1231 // Setup new ingress mcast role
1232 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).src().deviceId()),
1233 INGRESS);
1234
Pier Luigi580fd8a2018-01-16 10:47:50 +01001235 // For each link, modify the next on the source device adding the src port
1236 // and a new filter objective on the destination port
1237 links.forEach(link -> {
1238 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
Pier7b657162018-03-27 11:29:42 -07001239 mcastUtils.assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
1240 mcastUtils.addFilterToDevice(link.dst().deviceId(), link.dst().port(),
1241 mcastUtils.assignedVlan(null), mcastIp, null);
Pier Luigi580fd8a2018-01-16 10:47:50 +01001242 });
Pier1a7e0c02018-03-12 15:00:54 -07001243
1244 // Setup mcast role for the transit
1245 links.stream()
1246 .filter(link -> !link.src().deviceId().equals(source.deviceId()))
1247 .forEach(link -> mcastRoleStore.put(new McastStoreKey(mcastIp, link.src().deviceId()),
1248 TRANSIT));
Charles Chan72779502016-04-23 17:36:10 -07001249 }
1250
Charles Chanc91c8782016-03-30 17:54:24 -07001251 /**
Pier1f87aca2018-03-14 16:47:32 -07001252 * Go through all the paths, looking for shared links to be used
1253 * in the final path computation.
1254 *
1255 * @param egresses egress devices
1256 * @param availablePaths all the available paths towards the egress
1257 * @return shared links between egress devices
1258 */
1259 private Set<Link> exploreMcastTree(Set<DeviceId> egresses,
1260 Map<DeviceId, List<Path>> availablePaths) {
1261 // Length of the shortest path
1262 int minLength = Integer.MAX_VALUE;
1263 int length;
1264 // Current paths
1265 List<Path> currentPaths;
1266 // Verify the source can still reach all the egresses
1267 for (DeviceId egress : egresses) {
1268 // From the source we cannot reach all the sinks
Pier7b657162018-03-27 11:29:42 -07001269 // just continue and let's figure out after
Pier1f87aca2018-03-14 16:47:32 -07001270 currentPaths = availablePaths.get(egress);
1271 if (currentPaths.isEmpty()) {
1272 continue;
1273 }
1274 // Get the length of the first one available,
Pier7b657162018-03-27 11:29:42 -07001275 // update the min length
Pier1f87aca2018-03-14 16:47:32 -07001276 length = currentPaths.get(0).links().size();
1277 if (length < minLength) {
1278 minLength = length;
1279 }
Pier Luigi51ee7c02018-02-23 19:57:40 +01001280 }
Pier1f87aca2018-03-14 16:47:32 -07001281 // If there are no paths
1282 if (minLength == Integer.MAX_VALUE) {
1283 return Collections.emptySet();
1284 }
1285 // Iterate looking for shared links
1286 int index = 0;
1287 // Define the sets for the intersection
1288 Set<Link> sharedLinks = Sets.newHashSet();
1289 Set<Link> currentSharedLinks;
1290 Set<Link> currentLinks;
Pier7b657162018-03-27 11:29:42 -07001291 DeviceId egressToRemove = null;
Pier1f87aca2018-03-14 16:47:32 -07001292 // Let's find out the shared links
1293 while (index < minLength) {
1294 // Initialize the intersection with the paths related to the first egress
1295 currentPaths = availablePaths.get(
1296 egresses.stream()
1297 .findFirst()
1298 .orElse(null)
1299 );
1300 currentSharedLinks = Sets.newHashSet();
1301 // Iterate over the paths and take the "index" links
1302 for (Path path : currentPaths) {
1303 currentSharedLinks.add(path.links().get(index));
1304 }
1305 // Iterate over the remaining egress
1306 for (DeviceId egress : egresses) {
1307 // Iterate over the paths and take the "index" links
1308 currentLinks = Sets.newHashSet();
1309 for (Path path : availablePaths.get(egress)) {
1310 currentLinks.add(path.links().get(index));
1311 }
1312 // Do intersection
1313 currentSharedLinks = Sets.intersection(currentSharedLinks, currentLinks);
1314 // If there are no shared paths exit and record the device to remove
1315 // we have to retry with a subset of sinks
1316 if (currentSharedLinks.isEmpty()) {
Pier7b657162018-03-27 11:29:42 -07001317 egressToRemove = egress;
Pier1f87aca2018-03-14 16:47:32 -07001318 index = minLength;
1319 break;
1320 }
1321 }
1322 sharedLinks.addAll(currentSharedLinks);
1323 index++;
1324 }
1325 // If the shared links is empty and there are egress
1326 // let's retry another time with less sinks, we can
1327 // still build optimal subtrees
Pier7b657162018-03-27 11:29:42 -07001328 if (sharedLinks.isEmpty() && egresses.size() > 1 && egressToRemove != null) {
1329 egresses.remove(egressToRemove);
Pier1f87aca2018-03-14 16:47:32 -07001330 sharedLinks = exploreMcastTree(egresses, availablePaths);
1331 }
1332 return sharedLinks;
1333 }
1334
1335 /**
1336 * Build Mcast tree having as root the given source and as leaves the given egress points.
1337 *
1338 * @param source source of the tree
1339 * @param sinks leaves of the tree
1340 * @return the computed Mcast tree
1341 */
1342 private Map<ConnectPoint, List<Path>> computeSinkMcastTree(DeviceId source,
Pier7b657162018-03-27 11:29:42 -07001343 Set<ConnectPoint> sinks) {
Pier1f87aca2018-03-14 16:47:32 -07001344 // Get the egress devices, remove source from the egress if present
1345 Set<DeviceId> egresses = sinks.stream()
1346 .map(ConnectPoint::deviceId)
1347 .filter(deviceId -> !deviceId.equals(source))
1348 .collect(Collectors.toSet());
1349 Map<DeviceId, List<Path>> mcastTree = computeMcastTree(source, egresses);
Pier7b657162018-03-27 11:29:42 -07001350 // Build final tree and return it as it is
Pier1f87aca2018-03-14 16:47:32 -07001351 final Map<ConnectPoint, List<Path>> finalTree = Maps.newHashMap();
Pier7b657162018-03-27 11:29:42 -07001352 // We need to put back the source if it was originally present
1353 sinks.forEach(sink -> {
1354 List<Path> sinkPaths = mcastTree.get(sink.deviceId());
1355 finalTree.put(sink, sinkPaths != null ? sinkPaths : ImmutableList.of());
1356 });
Pier1f87aca2018-03-14 16:47:32 -07001357 return finalTree;
1358 }
1359
1360 /**
1361 * Build Mcast tree having as root the given source and as leaves the given egress.
1362 *
1363 * @param source source of the tree
1364 * @param egresses leaves of the tree
1365 * @return the computed Mcast tree
1366 */
1367 private Map<DeviceId, List<Path>> computeMcastTree(DeviceId source,
1368 Set<DeviceId> egresses) {
1369 // Pre-compute all the paths
1370 Map<DeviceId, List<Path>> availablePaths = Maps.newHashMap();
1371 // No links to enforce
1372 egresses.forEach(egress -> availablePaths.put(egress, getPaths(source, egress,
1373 Collections.emptySet())));
1374 // Explore the topology looking for shared links amongst the egresses
1375 Set<Link> linksToEnforce = exploreMcastTree(Sets.newHashSet(egresses), availablePaths);
1376 // Remove all the paths from the previous computation
1377 availablePaths.clear();
1378 // Build the final paths enforcing the shared links between egress devices
1379 egresses.forEach(egress -> availablePaths.put(egress, getPaths(source, egress,
1380 linksToEnforce)));
1381 return availablePaths;
1382 }
1383
1384 /**
1385 * Gets path from src to dst computed using the custom link weigher.
1386 *
1387 * @param src source device ID
1388 * @param dst destination device ID
1389 * @return list of paths from src to dst
1390 */
1391 private List<Path> getPaths(DeviceId src, DeviceId dst, Set<Link> linksToEnforce) {
1392 // Takes a snapshot of the topology
1393 final Topology currentTopology = topologyService.currentTopology();
1394 // Build a specific link weigher for this path computation
1395 final LinkWeigher linkWeigher = new SRLinkWeigher(srManager, src, linksToEnforce);
1396 // We will use our custom link weigher for our path
1397 // computations and build the list of valid paths
1398 List<Path> allPaths = Lists.newArrayList(
1399 topologyService.getPaths(currentTopology, src, dst, linkWeigher)
1400 );
1401 // If there are no valid paths, just exit
1402 log.debug("{} path(s) found from {} to {}", allPaths.size(), src, dst);
1403 return allPaths;
Pier Luigi51ee7c02018-02-23 19:57:40 +01001404 }
1405
Charles Chanc91c8782016-03-30 17:54:24 -07001406 /**
1407 * Gets a path from src to dst.
1408 * If a path was allocated before, returns the allocated path.
1409 * Otherwise, randomly pick one from available paths.
1410 *
1411 * @param src source device ID
1412 * @param dst destination device ID
1413 * @param mcastIp multicast group
Pier1f87aca2018-03-14 16:47:32 -07001414 * @param allPaths paths list
Charles Chanc91c8782016-03-30 17:54:24 -07001415 * @return an optional path from src to dst
1416 */
Pier1f87aca2018-03-14 16:47:32 -07001417 private Optional<Path> getPath(DeviceId src, DeviceId dst,
1418 IpAddress mcastIp, List<Path> allPaths) {
1419 // Firstly we get all the valid paths, if the supplied are null
1420 if (allPaths == null) {
1421 allPaths = getPaths(src, dst, Collections.emptySet());
1422 }
1423
1424 // If there are no paths just exit
Charles Chanc91c8782016-03-30 17:54:24 -07001425 if (allPaths.isEmpty()) {
Charles Chanc91c8782016-03-30 17:54:24 -07001426 return Optional.empty();
1427 }
1428
Pier Luigi91573e12018-01-23 16:06:38 +01001429 // Create a map index of suitablity-to-list of paths. For example
1430 // a path in the list associated to the index 1 shares only the
1431 // first hop and it is less suitable of a path belonging to the index
1432 // 2 that shares leaf-spine.
1433 Map<Integer, List<Path>> eligiblePaths = Maps.newHashMap();
1434 // Some init steps
1435 int nhop;
1436 McastStoreKey mcastStoreKey;
1437 Link hop;
1438 PortNumber srcPort;
1439 Set<PortNumber> existingPorts;
1440 NextObjective nextObj;
1441 // Iterate over paths looking for eligible paths
1442 for (Path path : allPaths) {
1443 // Unlikely, it will happen...
1444 if (!src.equals(path.links().get(0).src().deviceId())) {
1445 continue;
1446 }
1447 nhop = 0;
1448 // Iterate over the links
1449 while (nhop < path.links().size()) {
1450 // Get the link and verify if a next related
1451 // to the src device exist in the store
1452 hop = path.links().get(nhop);
1453 mcastStoreKey = new McastStoreKey(mcastIp, hop.src().deviceId());
1454 // It does not exist in the store, exit
1455 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1456 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001457 }
Pier Luigi91573e12018-01-23 16:06:38 +01001458 // Get the output ports on the next
1459 nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Pier7b657162018-03-27 11:29:42 -07001460 existingPorts = mcastUtils.getPorts(nextObj.next());
Pier Luigi91573e12018-01-23 16:06:38 +01001461 // And the src port on the link
1462 srcPort = hop.src().port();
1463 // the src port is not used as output, exit
1464 if (!existingPorts.contains(srcPort)) {
1465 break;
1466 }
1467 nhop++;
1468 }
1469 // n_hop defines the index
1470 if (nhop > 0) {
1471 eligiblePaths.compute(nhop, (index, paths) -> {
1472 paths = paths == null ? Lists.newArrayList() : paths;
1473 paths.add(path);
1474 return paths;
1475 });
Charles Chanc91c8782016-03-30 17:54:24 -07001476 }
1477 }
Pier Luigi91573e12018-01-23 16:06:38 +01001478
1479 // No suitable paths
1480 if (eligiblePaths.isEmpty()) {
1481 log.debug("No eligiblePath(s) found from {} to {}", src, dst);
1482 // Otherwise, randomly pick a path
1483 Collections.shuffle(allPaths);
1484 return allPaths.stream().findFirst();
1485 }
1486
1487 // Let's take the best ones
1488 Integer bestIndex = eligiblePaths.keySet()
1489 .stream()
1490 .sorted(Comparator.reverseOrder())
1491 .findFirst().orElse(null);
1492 List<Path> bestPaths = eligiblePaths.get(bestIndex);
1493 log.debug("{} eligiblePath(s) found from {} to {}",
1494 bestPaths.size(), src, dst);
1495 // randomly pick a path on the highest index
1496 Collections.shuffle(bestPaths);
1497 return bestPaths.stream().findFirst();
Charles Chanc91c8782016-03-30 17:54:24 -07001498 }
1499
1500 /**
Charles Chan72779502016-04-23 17:36:10 -07001501 * Gets device(s) of given role in given multicast group.
1502 *
1503 * @param mcastIp multicast IP
1504 * @param role multicast role
1505 * @return set of device ID or empty set if not found
1506 */
1507 private Set<DeviceId> getDevice(IpAddress mcastIp, McastRole role) {
1508 return mcastRoleStore.entrySet().stream()
1509 .filter(entry -> entry.getKey().mcastIp().equals(mcastIp) &&
1510 entry.getValue().value() == role)
Pier1f87aca2018-03-14 16:47:32 -07001511 .map(Entry::getKey).map(McastStoreKey::deviceId)
Charles Chan72779502016-04-23 17:36:10 -07001512 .collect(Collectors.toSet());
1513 }
1514
1515 /**
1516 * Gets groups which is affected by the link down event.
1517 *
1518 * @param link link going down
1519 * @return a set of multicast IpAddress
1520 */
1521 private Set<IpAddress> getAffectedGroups(Link link) {
1522 DeviceId deviceId = link.src().deviceId();
1523 PortNumber port = link.src().port();
1524 return mcastNextObjStore.entrySet().stream()
1525 .filter(entry -> entry.getKey().deviceId().equals(deviceId) &&
Pier7b657162018-03-27 11:29:42 -07001526 mcastUtils.getPorts(entry.getValue().value().next()).contains(port))
Pier1f87aca2018-03-14 16:47:32 -07001527 .map(Entry::getKey).map(McastStoreKey::mcastIp)
Charles Chan72779502016-04-23 17:36:10 -07001528 .collect(Collectors.toSet());
1529 }
1530
1531 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001532 * Gets groups which are affected by the device down event.
1533 *
1534 * @param deviceId device going down
1535 * @return a set of multicast IpAddress
1536 */
1537 private Set<IpAddress> getAffectedGroups(DeviceId deviceId) {
1538 return mcastNextObjStore.entrySet().stream()
1539 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
Pier1f87aca2018-03-14 16:47:32 -07001540 .map(Entry::getKey).map(McastStoreKey::mcastIp)
Pier Luigi580fd8a2018-01-16 10:47:50 +01001541 .collect(Collectors.toSet());
1542 }
1543
1544 /**
Charles Chan72779502016-04-23 17:36:10 -07001545 * Gets the spine-facing port on ingress device of given multicast group.
1546 *
1547 * @param mcastIp multicast IP
1548 * @return spine-facing port on ingress device
1549 */
Pier1a7e0c02018-03-12 15:00:54 -07001550 private Set<PortNumber> ingressTransitPort(IpAddress mcastIp) {
Pier979e61a2018-03-07 11:42:50 +01001551 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Charles Chan72779502016-04-23 17:36:10 -07001552 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -07001553 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Charles Chan72779502016-04-23 17:36:10 -07001554 if (ingressDevice != null) {
1555 NextObjective nextObj = mcastNextObjStore
1556 .get(new McastStoreKey(mcastIp, ingressDevice)).value();
Pier7b657162018-03-27 11:29:42 -07001557 Set<PortNumber> ports = mcastUtils.getPorts(nextObj.next());
Pier1a7e0c02018-03-12 15:00:54 -07001558 // Let's find out all the ingress-transit ports
Charles Chan72779502016-04-23 17:36:10 -07001559 for (PortNumber port : ports) {
1560 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001561 if (srManager.deviceConfiguration() != null &&
1562 srManager.deviceConfiguration().getPortSubnets(ingressDevice, port).isEmpty() &&
Charles Chan82f19972016-05-17 13:13:55 -07001563 !srManager.xConnectHandler.hasXConnect(new ConnectPoint(ingressDevice, port))) {
Pier1a7e0c02018-03-12 15:00:54 -07001564 portBuilder.add(port);
Charles Chan72779502016-04-23 17:36:10 -07001565 }
1566 }
1567 }
Pier1a7e0c02018-03-12 15:00:54 -07001568 return portBuilder.build();
Charles Chan72779502016-04-23 17:36:10 -07001569 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001570
1571 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001572 * Verify if the given device has sinks
1573 * for the multicast group.
1574 *
1575 * @param deviceId device Id
1576 * @param mcastIp multicast IP
1577 * @return true if the device has sink for the group.
1578 * False otherwise.
1579 */
1580 private boolean hasSinks(DeviceId deviceId, IpAddress mcastIp) {
1581 if (deviceId != null) {
1582 // Get the nextobjective
1583 Versioned<NextObjective> versionedNextObj = mcastNextObjStore.get(
1584 new McastStoreKey(mcastIp, deviceId)
1585 );
1586 // If it exists
1587 if (versionedNextObj != null) {
1588 NextObjective nextObj = versionedNextObj.value();
1589 // Retrieves all the output ports
Pier7b657162018-03-27 11:29:42 -07001590 Set<PortNumber> ports = mcastUtils.getPorts(nextObj.next());
Pier Luigi580fd8a2018-01-16 10:47:50 +01001591 // Tries to find at least one port that is not spine-facing
1592 for (PortNumber port : ports) {
1593 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001594 if (srManager.deviceConfiguration() != null &&
1595 (!srManager.deviceConfiguration().getPortSubnets(deviceId, port).isEmpty() ||
Pier Luigi580fd8a2018-01-16 10:47:50 +01001596 srManager.xConnectHandler.hasXConnect(new ConnectPoint(deviceId, port)))) {
1597 return true;
1598 }
1599 }
1600 }
1601 }
1602 return false;
1603 }
1604
1605 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +01001606 * Updates filtering objective for given device and port.
1607 * It is called in general when the mcast config has been
1608 * changed.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001609 *
1610 * @param deviceId device ID
1611 * @param portNum ingress port number
1612 * @param vlanId assigned VLAN ID
1613 * @param install true to add, false to remove
1614 */
Pier Luigi69f774d2018-02-28 12:10:50 +01001615 public void updateFilterToDevice(DeviceId deviceId, PortNumber portNum,
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001616 VlanId vlanId, boolean install) {
Pier Luigi35dab3f2018-01-25 16:16:02 +01001617 lastMcastChange = Instant.now();
1618 mcastLock();
1619 try {
1620 // Iterates over the route and updates properly the filtering objective
1621 // on the source device.
1622 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
Pier1f87aca2018-03-14 16:47:32 -07001623 // FIXME To be addressed with multiple sources support
1624 ConnectPoint source = srManager.multicastRouteService.sources(mcastRoute)
1625 .stream()
1626 .findFirst().orElse(null);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001627 if (source.deviceId().equals(deviceId) && source.port().equals(portNum)) {
1628 if (install) {
Pier7b657162018-03-27 11:29:42 -07001629 mcastUtils.addFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001630 } else {
Pier7b657162018-03-27 11:29:42 -07001631 mcastUtils.removeFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), null);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001632 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001633 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001634 });
1635 } finally {
1636 mcastUnlock();
1637 }
1638 }
1639
1640 /**
1641 * Performs bucket verification operation for all mcast groups in the devices.
1642 * Firstly, it verifies that mcast is stable before trying verification operation.
1643 * Verification consists in creating new nexts with VERIFY operation. Actually,
1644 * the operation is totally delegated to the driver.
1645 */
1646 private final class McastBucketCorrector implements Runnable {
1647
1648 @Override
1649 public void run() {
1650 // Verify if the Mcast has been stable for MCAST_STABLITY_THRESHOLD
1651 if (!isMcastStable()) {
1652 return;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001653 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001654 // Acquires lock
1655 mcastLock();
1656 try {
1657 // Iterates over the routes and verify the related next objectives
1658 srManager.multicastRouteService.getRoutes()
1659 .stream()
1660 .map(McastRoute::group)
1661 .forEach(mcastIp -> {
1662 log.trace("Running mcast buckets corrector for mcast group: {}",
1663 mcastIp);
1664
1665 // For each group we get current information in the store
1666 // and issue a check of the next objectives in place
Pier979e61a2018-03-07 11:42:50 +01001667 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +01001668 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -07001669 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +01001670 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi92e69be2018-03-02 12:53:37 +01001671 // Get source and sinks from Mcast Route Service and warn about errors
Pier7b657162018-03-27 11:29:42 -07001672 ConnectPoint source = mcastUtils.getSource(mcastIp);
1673 Set<ConnectPoint> sinks = mcastUtils.getSinks(mcastIp).values().stream()
1674 .flatMap(Collection::stream)
1675 .collect(Collectors.toSet());
Pier Luigi35dab3f2018-01-25 16:16:02 +01001676
1677 // Do not proceed if ingress device or source of this group are missing
1678 if (ingressDevice == null || source == null) {
Pier Luigi92e69be2018-03-02 12:53:37 +01001679 if (!sinks.isEmpty()) {
1680 log.warn("Unable to run buckets corrector. " +
1681 "Missing ingress {} or source {} for group {}",
1682 ingressDevice, source, mcastIp);
1683 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001684 return;
1685 }
1686
1687 // Continue only when this instance is the master of source device
1688 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1689 log.trace("Unable to run buckets corrector. " +
1690 "Skip {} due to lack of mastership " +
1691 "of the source device {}",
1692 mcastIp, source.deviceId());
1693 return;
1694 }
1695
1696 // Create the set of the devices to be processed
1697 ImmutableSet.Builder<DeviceId> devicesBuilder = ImmutableSet.builder();
1698 devicesBuilder.add(ingressDevice);
Pier1a7e0c02018-03-12 15:00:54 -07001699 if (!transitDevices.isEmpty()) {
1700 devicesBuilder.addAll(transitDevices);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001701 }
1702 if (!egressDevices.isEmpty()) {
1703 devicesBuilder.addAll(egressDevices);
1704 }
1705 Set<DeviceId> devicesToProcess = devicesBuilder.build();
1706
1707 // Iterate over the devices
1708 devicesToProcess.forEach(deviceId -> {
1709 McastStoreKey currentKey = new McastStoreKey(mcastIp, deviceId);
1710 // If next exists in our store verify related next objective
1711 if (mcastNextObjStore.containsKey(currentKey)) {
1712 NextObjective currentNext = mcastNextObjStore.get(currentKey).value();
1713 // Get current ports
Pier7b657162018-03-27 11:29:42 -07001714 Set<PortNumber> currentPorts = mcastUtils.getPorts(currentNext.next());
Pier Luigi35dab3f2018-01-25 16:16:02 +01001715 // Rebuild the next objective
Pier7b657162018-03-27 11:29:42 -07001716 currentNext = mcastUtils.nextObjBuilder(
Pier Luigi35dab3f2018-01-25 16:16:02 +01001717 mcastIp,
Pier7b657162018-03-27 11:29:42 -07001718 mcastUtils.assignedVlan(deviceId.equals(source.deviceId()) ?
1719 source : null),
Pier Luigi35dab3f2018-01-25 16:16:02 +01001720 currentPorts,
1721 currentNext.id()
1722 ).verify();
1723 // Send to the flowobjective service
1724 srManager.flowObjectiveService.next(deviceId, currentNext);
1725 } else {
Pier Luigid8a15162018-02-15 16:33:08 +01001726 log.warn("Unable to run buckets corrector. " +
Pier Luigi35dab3f2018-01-25 16:16:02 +01001727 "Missing next for {} and group {}",
1728 deviceId, mcastIp);
1729 }
1730 });
1731
1732 });
1733 } finally {
1734 // Finally, it releases the lock
1735 mcastUnlock();
1736 }
1737
1738 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001739 }
Pier Luigi0f9635b2018-01-15 18:06:43 +01001740
1741 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
1742 // If mcast ip is present
1743 if (mcastIp != null) {
1744 return mcastNextObjStore.entrySet().stream()
1745 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
Pier1f87aca2018-03-14 16:47:32 -07001746 .collect(Collectors.toMap(Entry::getKey,
Pier Luigi0f9635b2018-01-15 18:06:43 +01001747 entry -> entry.getValue().value().id()));
1748 }
1749 // Otherwise take all the groups
1750 return mcastNextObjStore.entrySet().stream()
Pier1f87aca2018-03-14 16:47:32 -07001751 .collect(Collectors.toMap(Entry::getKey,
Pier Luigi0f9635b2018-01-15 18:06:43 +01001752 entry -> entry.getValue().value().id()));
1753 }
1754
Pier Luigi69f774d2018-02-28 12:10:50 +01001755 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +01001756 // If mcast ip is present
1757 if (mcastIp != null) {
1758 return mcastRoleStore.entrySet().stream()
1759 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
Pier1f87aca2018-03-14 16:47:32 -07001760 .collect(Collectors.toMap(Entry::getKey,
Pier Luigi0f9635b2018-01-15 18:06:43 +01001761 entry -> entry.getValue().value()));
1762 }
1763 // Otherwise take all the groups
1764 return mcastRoleStore.entrySet().stream()
Pier1f87aca2018-03-14 16:47:32 -07001765 .collect(Collectors.toMap(Entry::getKey,
Pier Luigi0f9635b2018-01-15 18:06:43 +01001766 entry -> entry.getValue().value()));
1767 }
1768
1769 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
1770 Map<ConnectPoint, List<ConnectPoint>> mcastPaths = Maps.newHashMap();
1771 // Get the source
Pier7b657162018-03-27 11:29:42 -07001772 ConnectPoint source = mcastUtils.getSource(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +01001773 // Source cannot be null, we don't know the starting point
1774 if (source != null) {
1775 // Init steps
1776 Set<DeviceId> visited = Sets.newHashSet();
1777 List<ConnectPoint> currentPath = Lists.newArrayList(
1778 source
1779 );
1780 // Build recursively the mcast paths
1781 buildMcastPaths(source.deviceId(), visited, mcastPaths, currentPath, mcastIp);
1782 }
1783 return mcastPaths;
1784 }
1785
1786 private void buildMcastPaths(DeviceId toVisit, Set<DeviceId> visited,
1787 Map<ConnectPoint, List<ConnectPoint>> mcastPaths,
1788 List<ConnectPoint> currentPath, IpAddress mcastIp) {
1789 // If we have visited the node to visit
1790 // there is a loop
1791 if (visited.contains(toVisit)) {
1792 return;
1793 }
1794 // Visit next-hop
1795 visited.add(toVisit);
1796 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, toVisit);
1797 // Looking for next-hops
1798 if (mcastNextObjStore.containsKey(mcastStoreKey)) {
1799 // Build egress connectpoints
1800 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
1801 // Get Ports
Pier7b657162018-03-27 11:29:42 -07001802 Set<PortNumber> outputPorts = mcastUtils.getPorts(nextObjective.next());
Pier Luigi0f9635b2018-01-15 18:06:43 +01001803 // Build relative cps
1804 ImmutableSet.Builder<ConnectPoint> cpBuilder = ImmutableSet.builder();
1805 outputPorts.forEach(portNumber -> cpBuilder.add(new ConnectPoint(toVisit, portNumber)));
1806 Set<ConnectPoint> egressPoints = cpBuilder.build();
1807 // Define other variables for the next steps
1808 Set<Link> egressLinks;
1809 List<ConnectPoint> newCurrentPath;
1810 Set<DeviceId> newVisited;
1811 DeviceId newToVisit;
1812 for (ConnectPoint egressPoint : egressPoints) {
1813 egressLinks = srManager.linkService.getEgressLinks(egressPoint);
1814 // If it does not have egress links, stop
1815 if (egressLinks.isEmpty()) {
1816 // Add the connect points to the path
1817 newCurrentPath = Lists.newArrayList(currentPath);
1818 newCurrentPath.add(0, egressPoint);
1819 // Save in the map
1820 mcastPaths.put(egressPoint, newCurrentPath);
1821 } else {
1822 newVisited = Sets.newHashSet(visited);
1823 // Iterate over the egress links for the next hops
1824 for (Link egressLink : egressLinks) {
1825 // Update to visit
1826 newToVisit = egressLink.dst().deviceId();
1827 // Add the connect points to the path
1828 newCurrentPath = Lists.newArrayList(currentPath);
1829 newCurrentPath.add(0, egressPoint);
1830 newCurrentPath.add(0, egressLink.dst());
1831 // Go to the next hop
1832 buildMcastPaths(newToVisit, newVisited, mcastPaths, newCurrentPath, mcastIp);
1833 }
1834 }
1835 }
1836 }
1837 }
1838
Charles Chanc91c8782016-03-30 17:54:24 -07001839}