blob: 51a4524b37a279b5867a7a3ffc265d573008a9e9 [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;
Charles Chanc91c8782016-03-30 17:54:24 -070023import com.google.common.collect.ImmutableSet;
24import com.google.common.collect.Lists;
Pier Luigi91573e12018-01-23 16:06:38 +010025import com.google.common.collect.Maps;
Charles Chanc91c8782016-03-30 17:54:24 -070026import com.google.common.collect.Sets;
27import org.onlab.packet.Ethernet;
28import org.onlab.packet.IpAddress;
29import org.onlab.packet.IpPrefix;
30import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
32import org.onlab.util.KryoNamespace;
Pier Luigi580fd8a2018-01-16 10:47:50 +010033import org.onosproject.cluster.NodeId;
Charles Chanc91c8782016-03-30 17:54:24 -070034import org.onosproject.core.ApplicationId;
35import org.onosproject.core.CoreService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070036import org.onosproject.net.config.basics.McastConfig;
Charles Chanc91c8782016-03-30 17:54:24 -070037import org.onosproject.net.ConnectPoint;
38import org.onosproject.net.DeviceId;
39import org.onosproject.net.Link;
40import org.onosproject.net.Path;
41import org.onosproject.net.PortNumber;
42import org.onosproject.net.flow.DefaultTrafficSelector;
43import org.onosproject.net.flow.DefaultTrafficTreatment;
44import org.onosproject.net.flow.TrafficSelector;
45import org.onosproject.net.flow.TrafficTreatment;
46import org.onosproject.net.flow.criteria.Criteria;
Pier Luigid29ca7c2018-02-28 17:24:03 +010047import org.onosproject.net.flow.criteria.VlanIdCriterion;
Charles Chanc91c8782016-03-30 17:54:24 -070048import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
49import org.onosproject.net.flowobjective.DefaultFilteringObjective;
50import org.onosproject.net.flowobjective.DefaultForwardingObjective;
51import org.onosproject.net.flowobjective.DefaultNextObjective;
Charles Chan72779502016-04-23 17:36:10 -070052import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Charles Chanc91c8782016-03-30 17:54:24 -070053import org.onosproject.net.flowobjective.FilteringObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective;
55import org.onosproject.net.flowobjective.NextObjective;
Charles Chan72779502016-04-23 17:36:10 -070056import org.onosproject.net.flowobjective.ObjectiveContext;
Charles Chanc91c8782016-03-30 17:54:24 -070057import org.onosproject.net.mcast.McastEvent;
Pier Luigi35dab3f2018-01-25 16:16:02 +010058import org.onosproject.net.mcast.McastRoute;
Charles Chanc91c8782016-03-30 17:54:24 -070059import org.onosproject.net.mcast.McastRouteInfo;
Pier Luigid8a15162018-02-15 16:33:08 +010060import org.onosproject.net.topology.Topology;
Charles Chanc91c8782016-03-30 17:54:24 -070061import org.onosproject.net.topology.TopologyService;
Pier Luigi69f774d2018-02-28 12:10:50 +010062import org.onosproject.segmentrouting.SegmentRoutingManager;
63import org.onosproject.segmentrouting.SegmentRoutingService;
Pier Luigi51ee7c02018-02-23 19:57:40 +010064import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
Charles Chan370a65b2016-05-10 17:29:47 -070065import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Charles Chan72779502016-04-23 17:36:10 -070066import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chanc91c8782016-03-30 17:54:24 -070067import org.onosproject.store.serializers.KryoNamespaces;
68import org.onosproject.store.service.ConsistentMap;
69import org.onosproject.store.service.Serializer;
70import org.onosproject.store.service.StorageService;
Pier Luigi580fd8a2018-01-16 10:47:50 +010071import org.onosproject.store.service.Versioned;
Charles Chanc91c8782016-03-30 17:54:24 -070072import org.slf4j.Logger;
73import org.slf4j.LoggerFactory;
74
Pier Luigi35dab3f2018-01-25 16:16:02 +010075import java.time.Instant;
Charles Chanc91c8782016-03-30 17:54:24 -070076import java.util.Collection;
77import java.util.Collections;
Pier Luigi91573e12018-01-23 16:06:38 +010078import java.util.Comparator;
Charles Chanc91c8782016-03-30 17:54:24 -070079import java.util.List;
Charles Chan72779502016-04-23 17:36:10 -070080import java.util.Map;
Charles Chanc91c8782016-03-30 17:54:24 -070081import java.util.Optional;
82import java.util.Set;
Pier Luigi35dab3f2018-01-25 16:16:02 +010083import java.util.concurrent.ScheduledExecutorService;
84import java.util.concurrent.TimeUnit;
85import java.util.concurrent.locks.Lock;
86import java.util.concurrent.locks.ReentrantLock;
Charles Chan72779502016-04-23 17:36:10 -070087import java.util.stream.Collectors;
88
89import static com.google.common.base.Preconditions.checkState;
Pier Luigi35dab3f2018-01-25 16:16:02 +010090import static java.util.concurrent.Executors.newScheduledThreadPool;
91import static org.onlab.util.Tools.groupedThreads;
Pier Luigid29ca7c2018-02-28 17:24:03 +010092import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
93import static org.onosproject.net.mcast.McastEvent.Type.ROUTE_REMOVED;
94import static org.onosproject.net.mcast.McastEvent.Type.SOURCE_ADDED;
95import static org.onosproject.net.mcast.McastEvent.Type.SOURCE_UPDATED;
Charles Chan10b0fb72017-02-02 16:20:42 -080096import static org.onosproject.segmentrouting.SegmentRoutingManager.INTERNAL_VLAN;
Charles Chanc91c8782016-03-30 17:54:24 -070097
98/**
Pier Luigi69f774d2018-02-28 12:10:50 +010099 * Handles Multicast related events.
Charles Chanc91c8782016-03-30 17:54:24 -0700100 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700101public class McastHandler {
102 private static final Logger log = LoggerFactory.getLogger(McastHandler.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700103 private final SegmentRoutingManager srManager;
104 private final ApplicationId coreAppId;
Charles Chan82f19972016-05-17 13:13:55 -0700105 private final StorageService storageService;
106 private final TopologyService topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700107 private final ConsistentMap<McastStoreKey, NextObjective> mcastNextObjStore;
108 private final KryoNamespace.Builder mcastKryo;
109 private final ConsistentMap<McastStoreKey, McastRole> mcastRoleStore;
110
Pier Luigid29ca7c2018-02-28 17:24:03 +0100111 // Wait time for the cache
112 private static final int WAIT_TIME_MS = 1000;
113 /**
114 * The mcastEventCache is implemented to avoid race condition by giving more time to the
115 * underlying subsystems to process previous calls.
116 */
117 private Cache<McastCacheKey, McastEvent> mcastEventCache = CacheBuilder.newBuilder()
118 .expireAfterWrite(WAIT_TIME_MS, TimeUnit.MILLISECONDS)
119 .removalListener((RemovalNotification<McastCacheKey, McastEvent> notification) -> {
120 // Get group ip, sink and related event
121 IpAddress mcastIp = notification.getKey().mcastIp();
122 ConnectPoint sink = notification.getKey().sink();
123 McastEvent mcastEvent = notification.getValue();
124 RemovalCause cause = notification.getCause();
125 log.debug("mcastEventCache removal event. group={}, sink={}, mcastEvent={}, cause={}",
126 mcastIp, sink, mcastEvent, cause);
127 // If it expires or it has been replaced, we deque the event
128 switch (notification.getCause()) {
129 case REPLACED:
130 case EXPIRED:
131 dequeueMcastEvent(mcastEvent);
132 break;
133 default:
134 break;
135 }
136 }).build();
137
138 private void enqueueMcastEvent(McastEvent mcastEvent) {
139 log.debug("Enqueue mcastEvent {}", mcastEvent);
140 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
141 // Let's create the keys of the cache
142 ImmutableSet.Builder<ConnectPoint> sinksBuilder = ImmutableSet.builder();
143 // For this event we will have a set of sinks
144 if (mcastEvent.type() == SOURCE_ADDED ||
145 mcastEvent.type() == SOURCE_UPDATED ||
146 mcastEvent.type() == ROUTE_REMOVED) {
147 // Add all the sinks
148 sinksBuilder.addAll(mcastRouteInfo.sinks());
149 } else {
150 // We have just one sink in this case
151 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
152 // It is always true, unless something of bad happened
153 // in the mcast route store
154 if (sink != null) {
155 sinksBuilder.add(sink);
156 }
157 }
158 // Push the elements in the cache
159 sinksBuilder.build().forEach(sink -> {
160 McastCacheKey cacheKey = new McastCacheKey(mcastRouteInfo.route().group(),
161 sink);
162 mcastEventCache.put(cacheKey, mcastEvent);
163 });
164 }
165
166 private void dequeueMcastEvent(McastEvent mcastEvent) {
167 log.debug("Dequeue mcastEvent {}", mcastEvent);
168 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
169 // Get source, mcast group
170 ConnectPoint source = mcastRouteInfo.source().orElse(null);
171 IpAddress mcastIp = mcastRouteInfo.route().group();
172 // According to the event type let's call the proper method
173 switch (mcastEvent.type()) {
174 case SOURCE_ADDED:
175 // Get all the sinks and process
176 Set<ConnectPoint> sinks = mcastRouteInfo.sinks();
177 sinks.forEach(sink -> processSinkAddedInternal(source, sink, mcastIp));
178 break;
179 case SOURCE_UPDATED:
180 // Get old source
181 ConnectPoint oldSource = mcastEvent.prevSubject().source().orElse(null);
182 // Just the first cached element will be processed
183 processSourceUpdatedInternal(mcastIp, source, oldSource);
184 break;
185 case ROUTE_REMOVED:
186 // Process the route removed, just the first cached element will be processed
187 processRouteRemovedInternal(source, mcastIp);
188 break;
189 case SINK_ADDED:
190 // Get the only sink and process
191 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
192 processSinkAddedInternal(source, sink, mcastIp);
193 break;
194 case SINK_REMOVED:
195 sink = mcastRouteInfo.sink().orElse(null);
196 processSinkRemovedInternal(source, sink, mcastIp);
197 break;
198 default:
199 break;
200 }
201 }
202
Pier Luigi35dab3f2018-01-25 16:16:02 +0100203 // Mcast lock to serialize local operations
204 private final Lock mcastLock = new ReentrantLock();
205
206 /**
207 * Acquires the lock used when making mcast changes.
208 */
209 private void mcastLock() {
210 mcastLock.lock();
211 }
212
213 /**
214 * Releases the lock used when making mcast changes.
215 */
216 private void mcastUnlock() {
217 mcastLock.unlock();
218 }
219
220 // Stability threshold for Mcast. Seconds
221 private static final long MCAST_STABLITY_THRESHOLD = 5;
222 // Last change done
223 private Instant lastMcastChange = Instant.now();
224
225 /**
226 * Determines if mcast in the network has been stable in the last
227 * MCAST_STABLITY_THRESHOLD seconds, by comparing the current time
228 * to the last mcast change timestamp.
229 *
230 * @return true if stable
231 */
232 private boolean isMcastStable() {
233 long last = (long) (lastMcastChange.toEpochMilli() / 1000.0);
234 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das97241862018-02-14 14:14:54 -0800235 log.trace("Mcast stable since {}s", now - last);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100236 return (now - last) > MCAST_STABLITY_THRESHOLD;
237 }
238
239 // Verify interval for Mcast
240 private static final long MCAST_VERIFY_INTERVAL = 30;
241
242 // Executor for mcast bucket corrector
243 private ScheduledExecutorService executorService
Pier Luigid29ca7c2018-02-28 17:24:03 +0100244 = newScheduledThreadPool(1, groupedThreads("mcastWorker", "mcastWorker-%d", log));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100245
Charles Chan72779502016-04-23 17:36:10 -0700246 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700247 * Constructs the McastEventHandler.
248 *
249 * @param srManager Segment Routing manager
250 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700251 public McastHandler(SegmentRoutingManager srManager) {
Charles Chanc91c8782016-03-30 17:54:24 -0700252 coreAppId = srManager.coreService.getAppId(CoreService.CORE_APP_NAME);
Charles Chanc91c8782016-03-30 17:54:24 -0700253 this.srManager = srManager;
254 this.storageService = srManager.storageService;
255 this.topologyService = srManager.topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700256 mcastKryo = new KryoNamespace.Builder()
Charles Chanc91c8782016-03-30 17:54:24 -0700257 .register(KryoNamespaces.API)
Charles Chan72779502016-04-23 17:36:10 -0700258 .register(McastStoreKey.class)
259 .register(McastRole.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700260 mcastNextObjStore = storageService
Charles Chan72779502016-04-23 17:36:10 -0700261 .<McastStoreKey, NextObjective>consistentMapBuilder()
Charles Chanc91c8782016-03-30 17:54:24 -0700262 .withName("onos-mcast-nextobj-store")
Charles Chan4922a172016-05-23 16:45:45 -0700263 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-NextObj")))
Charles Chanc91c8782016-03-30 17:54:24 -0700264 .build();
Charles Chan72779502016-04-23 17:36:10 -0700265 mcastRoleStore = storageService
266 .<McastStoreKey, McastRole>consistentMapBuilder()
267 .withName("onos-mcast-role-store")
Charles Chan4922a172016-05-23 16:45:45 -0700268 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-Role")))
Charles Chan72779502016-04-23 17:36:10 -0700269 .build();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100270 // Init the executor service and the buckets corrector
271 executorService.scheduleWithFixedDelay(new McastBucketCorrector(), 10,
272 MCAST_VERIFY_INTERVAL,
273 TimeUnit.SECONDS);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100274 // Schedule the clean up, this will allow the processing of the expired events
275 executorService.scheduleAtFixedRate(mcastEventCache::cleanUp, 0,
276 WAIT_TIME_MS, TimeUnit.MILLISECONDS);
Charles Chan72779502016-04-23 17:36:10 -0700277 }
278
279 /**
280 * Read initial multicast from mcast store.
281 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100282 public void init() {
Charles Chan72779502016-04-23 17:36:10 -0700283 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
284 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
285 Set<ConnectPoint> sinks = srManager.multicastRouteService.fetchSinks(mcastRoute);
286 sinks.forEach(sink -> {
287 processSinkAddedInternal(source, sink, mcastRoute.group());
288 });
289 });
Charles Chanc91c8782016-03-30 17:54:24 -0700290 }
291
292 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100293 * Clean up when deactivating the application.
294 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100295 public void terminate() {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100296 executorService.shutdown();
297 }
298
299 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +0100300 * Processes the SOURCE_ADDED, SOURCE_UPDATED, SINK_ADDED,
301 * SINK_REMOVED and ROUTE_REMOVED events.
Charles Chanc91c8782016-03-30 17:54:24 -0700302 *
303 * @param event McastEvent with SOURCE_ADDED type
304 */
Pier Luigid29ca7c2018-02-28 17:24:03 +0100305 public void processMcastEvent(McastEvent event) {
306 log.info("process {}", event);
307 // Verify if it is a complete event
Charles Chanc91c8782016-03-30 17:54:24 -0700308 McastRouteInfo mcastRouteInfo = event.subject();
309 if (!mcastRouteInfo.isComplete()) {
Pier Luigid29ca7c2018-02-28 17:24:03 +0100310 log.info("Incompleted McastRouteInfo. Abort {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -0700311 return;
312 }
Pier Luigid29ca7c2018-02-28 17:24:03 +0100313 // Just enqueue for now
314 enqueueMcastEvent(event);
Pier Luigi6786b922018-02-02 16:19:11 +0100315 }
316
317 /**
Pier Luigie80d6b42018-02-26 12:31:38 +0100318 * Process the SOURCE_UPDATED event.
319 *
320 * @param newSource the updated srouce info
321 * @param oldSource the outdated source info
322 */
323 private void processSourceUpdatedInternal(IpAddress mcastIp,
324 ConnectPoint newSource,
325 ConnectPoint oldSource) {
326 lastMcastChange = Instant.now();
327 mcastLock();
328 try {
329 log.debug("Processing source updated for group {}", mcastIp);
330
331 // Build key for the store and retrieve old data
332 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, oldSource.deviceId());
333
334 // Verify leadership on the operation
335 if (!isLeader(oldSource)) {
336 log.debug("Skip {} due to lack of leadership", mcastIp);
337 return;
338 }
339
340 // This device is not serving this multicast group
341 if (!mcastRoleStore.containsKey(mcastStoreKey) ||
342 !mcastNextObjStore.containsKey(mcastStoreKey)) {
343 log.warn("{} is not serving {}. Abort.", oldSource.deviceId(), mcastIp);
344 return;
345 }
346 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
347 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
348
Pier Luigid29ca7c2018-02-28 17:24:03 +0100349 // This an optimization to avoid unnecessary removal and add
350 if (!assignedVlanFromNext(nextObjective).equals(assignedVlan(newSource))) {
351 // Let's remove old flows and groups
352 removeGroupFromDevice(oldSource.deviceId(), mcastIp, assignedVlan(oldSource));
353 // Push new flows and group
354 outputPorts.forEach(portNumber -> addPortToDevice(newSource.deviceId(), portNumber,
355 mcastIp, assignedVlan(newSource)));
356 }
Pier Luigie80d6b42018-02-26 12:31:38 +0100357 addFilterToDevice(newSource.deviceId(), newSource.port(),
358 assignedVlan(newSource), mcastIp);
359 // Setup mcast roles
360 mcastRoleStore.put(new McastStoreKey(mcastIp, newSource.deviceId()),
361 McastRole.INGRESS);
362 } finally {
363 mcastUnlock();
364 }
365 }
366
367 /**
Pier Luigi6786b922018-02-02 16:19:11 +0100368 * Removes the entire mcast tree related to this group.
369 *
370 * @param mcastIp multicast group IP address
371 */
372 private void processRouteRemovedInternal(ConnectPoint source, IpAddress mcastIp) {
373 lastMcastChange = Instant.now();
374 mcastLock();
375 try {
Pier Luigie80d6b42018-02-26 12:31:38 +0100376 log.debug("Processing route removed for group {}", mcastIp);
Pier Luigi6786b922018-02-02 16:19:11 +0100377
378 // Find out the ingress, transit and egress device of the affected group
379 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
380 .stream().findAny().orElse(null);
381 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
382 .stream().findAny().orElse(null);
383 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
384
385 // Verify leadership on the operation
386 if (!isLeader(source)) {
387 log.debug("Skip {} due to lack of leadership", mcastIp);
388 return;
389 }
390
391 // If there are egress devices, sinks could be only on the ingress
392 if (!egressDevices.isEmpty()) {
393 egressDevices.forEach(
394 deviceId -> removeGroupFromDevice(deviceId, mcastIp, assignedVlan(null))
395 );
396 }
397 // Transit could be null
398 if (transitDevice != null) {
399 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
400 }
401 // Ingress device should be not null
402 if (ingressDevice != null) {
403 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
404 }
Pier Luigi6786b922018-02-02 16:19:11 +0100405 } finally {
406 mcastUnlock();
407 }
408 }
409
410 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100411 * Removes a path from source to sink for given multicast group.
412 *
413 * @param source connect point of the multicast source
414 * @param sink connection point of the multicast sink
415 * @param mcastIp multicast group IP address
416 */
417 private void processSinkRemovedInternal(ConnectPoint source, ConnectPoint sink,
418 IpAddress mcastIp) {
419 lastMcastChange = Instant.now();
420 mcastLock();
421 try {
Pier Luigi6786b922018-02-02 16:19:11 +0100422 // Verify leadership on the operation
423 if (!isLeader(source)) {
424 log.debug("Skip {} due to lack of leadership", mcastIp);
Charles Chanc91c8782016-03-30 17:54:24 -0700425 return;
426 }
Charles Chanc91c8782016-03-30 17:54:24 -0700427
Pier Luigi35dab3f2018-01-25 16:16:02 +0100428 // When source and sink are on the same device
429 if (source.deviceId().equals(sink.deviceId())) {
430 // Source and sink are on even the same port. There must be something wrong.
431 if (source.port().equals(sink.port())) {
432 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
433 mcastIp, sink, source);
434 return;
435 }
436 removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
437 return;
438 }
Charles Chanc91c8782016-03-30 17:54:24 -0700439
Pier Luigi35dab3f2018-01-25 16:16:02 +0100440 // Process the egress device
441 boolean isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
442 if (isLast) {
443 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
444 }
445
446 // If this is the last sink on the device, also update upstream
447 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
448 if (mcastPath.isPresent()) {
449 List<Link> links = Lists.newArrayList(mcastPath.get().links());
450 Collections.reverse(links);
451 for (Link link : links) {
452 if (isLast) {
453 isLast = removePortFromDevice(
454 link.src().deviceId(),
455 link.src().port(),
456 mcastIp,
457 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null)
458 );
459 mcastRoleStore.remove(new McastStoreKey(mcastIp, link.src().deviceId()));
460 }
Charles Chanc91c8782016-03-30 17:54:24 -0700461 }
462 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100463 } finally {
464 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700465 }
466 }
467
468 /**
469 * Establishes a path from source to sink for given multicast group.
470 *
471 * @param source connect point of the multicast source
472 * @param sink connection point of the multicast sink
473 * @param mcastIp multicast group IP address
474 */
475 private void processSinkAddedInternal(ConnectPoint source, ConnectPoint sink,
476 IpAddress mcastIp) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100477 lastMcastChange = Instant.now();
478 mcastLock();
479 try {
480 // Continue only when this instance is the master of source device
481 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
482 log.debug("Skip {} due to lack of mastership of the source device {}",
483 mcastIp, source.deviceId());
Charles Chanc91c8782016-03-30 17:54:24 -0700484 return;
485 }
Charles Chanc91c8782016-03-30 17:54:24 -0700486
Pier Luigi35dab3f2018-01-25 16:16:02 +0100487 // Process the ingress device
488 addFilterToDevice(source.deviceId(), source.port(), assignedVlan(source), mcastIp);
Charles Chan72779502016-04-23 17:36:10 -0700489
Pier Luigi35dab3f2018-01-25 16:16:02 +0100490 // When source and sink are on the same device
491 if (source.deviceId().equals(sink.deviceId())) {
492 // Source and sink are on even the same port. There must be something wrong.
493 if (source.port().equals(sink.port())) {
494 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
495 mcastIp, sink, source);
496 return;
497 }
498 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
499 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()), McastRole.INGRESS);
500 return;
501 }
Charles Chan72779502016-04-23 17:36:10 -0700502
Pier Luigi35dab3f2018-01-25 16:16:02 +0100503 // Find a path. If present, create/update groups and flows for each hop
504 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
505 if (mcastPath.isPresent()) {
506 List<Link> links = mcastPath.get().links();
507 checkState(links.size() == 2,
508 "Path in leaf-spine topology should always be two hops: ", links);
Charles Chan72779502016-04-23 17:36:10 -0700509
Pier Luigi35dab3f2018-01-25 16:16:02 +0100510 links.forEach(link -> {
511 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
512 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
513 addFilterToDevice(link.dst().deviceId(), link.dst().port(), assignedVlan(null), mcastIp);
514 });
515
516 // Process the egress device
517 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
518
519 // Setup mcast roles
520 mcastRoleStore.put(new McastStoreKey(mcastIp, source.deviceId()),
521 McastRole.INGRESS);
522 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
523 McastRole.TRANSIT);
524 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()),
525 McastRole.EGRESS);
526 } else {
527 log.warn("Unable to find a path from {} to {}. Abort sinkAdded",
528 source.deviceId(), sink.deviceId());
529 }
530 } finally {
531 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700532 }
533 }
534
535 /**
Charles Chan72779502016-04-23 17:36:10 -0700536 * Processes the LINK_DOWN event.
537 *
538 * @param affectedLink Link that is going down
539 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100540 public void processLinkDown(Link affectedLink) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100541 lastMcastChange = Instant.now();
542 mcastLock();
543 try {
544 // Get groups affected by the link down event
545 getAffectedGroups(affectedLink).forEach(mcastIp -> {
546 // TODO Optimize when the group editing is in place
547 log.debug("Processing link down {} for group {}",
548 affectedLink, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100549
Pier Luigi35dab3f2018-01-25 16:16:02 +0100550 // Find out the ingress, transit and egress device of affected group
551 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
552 .stream().findAny().orElse(null);
553 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
554 .stream().findAny().orElse(null);
555 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
556 ConnectPoint source = getSource(mcastIp);
Charles Chana8f9dee2016-05-16 18:44:13 -0700557
Pier Luigi35dab3f2018-01-25 16:16:02 +0100558 // Do not proceed if any of these info is missing
559 if (ingressDevice == null || transitDevice == null
560 || egressDevices == null || source == null) {
561 log.warn("Missing ingress {}, transit {}, egress {} devices or source {}",
562 ingressDevice, transitDevice, egressDevices, source);
563 return;
Charles Chan72779502016-04-23 17:36:10 -0700564 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100565
566 // Continue only when this instance is the master of source device
567 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
568 log.debug("Skip {} due to lack of mastership of the source device {}",
569 source.deviceId());
570 return;
571 }
572
573 // Remove entire transit
574 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
575
576 // Remove transit-facing port on ingress device
577 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
578 if (ingressTransitPort != null) {
579 removePortFromDevice(ingressDevice, ingressTransitPort, mcastIp, assignedVlan(source));
580 mcastRoleStore.remove(new McastStoreKey(mcastIp, transitDevice));
581 }
582
583 // Construct a new path for each egress device
584 egressDevices.forEach(egressDevice -> {
585 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
586 if (mcastPath.isPresent()) {
587 installPath(mcastIp, source, mcastPath.get());
588 } else {
589 log.warn("Fail to recover egress device {} from link failure {}",
590 egressDevice, affectedLink);
591 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
592 }
593 });
Charles Chan72779502016-04-23 17:36:10 -0700594 });
Pier Luigi35dab3f2018-01-25 16:16:02 +0100595 } finally {
596 mcastUnlock();
597 }
Charles Chan72779502016-04-23 17:36:10 -0700598 }
599
600 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +0100601 * Process the DEVICE_DOWN event.
602 *
603 * @param deviceDown device going down
604 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100605 public void processDeviceDown(DeviceId deviceDown) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100606 lastMcastChange = Instant.now();
607 mcastLock();
608 try {
609 // Get the mcast groups affected by the device going down
610 getAffectedGroups(deviceDown).forEach(mcastIp -> {
611 // TODO Optimize when the group editing is in place
612 log.debug("Processing device down {} for group {}",
613 deviceDown, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100614
Pier Luigi35dab3f2018-01-25 16:16:02 +0100615 // Find out the ingress, transit and egress device of affected group
616 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
617 .stream().findAny().orElse(null);
618 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
619 .stream().findAny().orElse(null);
620 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
621 ConnectPoint source = getSource(mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100622
Pier Luigi35dab3f2018-01-25 16:16:02 +0100623 // Do not proceed if ingress device or source of this group are missing
624 // If sinks are in other leafs, we have ingress, transit, egress, and source
625 // If sinks are in the same leaf, we have just ingress and source
626 if (ingressDevice == null || source == null) {
627 log.warn("Missing ingress {} or source {} for group {}",
628 ingressDevice, source, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100629 return;
630 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100631
Pier Luigi6786b922018-02-02 16:19:11 +0100632 // Verify leadership on the operation
633 if (!isLeader(source)) {
634 log.debug("Skip {} due to lack of leadership", mcastIp);
635 return;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100636 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100637
638 // If it exists, we have to remove it in any case
639 if (transitDevice != null) {
640 // Remove entire transit
641 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
642 }
643 // If the ingress is down
644 if (ingressDevice.equals(deviceDown)) {
645 // Remove entire ingress
646 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
647 // If other sinks different from the ingress exist
648 if (!egressDevices.isEmpty()) {
649 // Remove all the remaining egress
650 egressDevices.forEach(
651 egressDevice -> removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null))
652 );
Pier Luigi580fd8a2018-01-16 10:47:50 +0100653 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100654 } else {
655 // Egress or transit could be down at this point
656 // Get the ingress-transit port if it exists
657 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
658 if (ingressTransitPort != null) {
659 // Remove transit-facing port on ingress device
660 removePortFromDevice(ingressDevice, ingressTransitPort, mcastIp, assignedVlan(source));
661 }
662 // One of the egress device is down
663 if (egressDevices.contains(deviceDown)) {
664 // Remove entire device down
665 removeGroupFromDevice(deviceDown, mcastIp, assignedVlan(null));
666 // Remove the device down from egress
667 egressDevices.remove(deviceDown);
668 // If there are no more egress and ingress does not have sinks
669 if (egressDevices.isEmpty() && !hasSinks(ingressDevice, mcastIp)) {
670 // Remove entire ingress
671 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
672 // We have done
673 return;
674 }
675 }
676 // Construct a new path for each egress device
677 egressDevices.forEach(egressDevice -> {
678 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
679 // If there is a new path
680 if (mcastPath.isPresent()) {
681 // Let's install the new mcast path for this egress
682 installPath(mcastIp, source, mcastPath.get());
683 } else {
684 // We were not able to find an alternative path for this egress
685 log.warn("Fail to recover egress device {} from device down {}",
686 egressDevice, deviceDown);
687 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
688 }
689 });
690 }
691 });
692 } finally {
693 mcastUnlock();
694 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100695 }
696
697 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700698 * Adds filtering objective for given device and port.
699 *
700 * @param deviceId device ID
701 * @param port ingress port number
702 * @param assignedVlan assigned VLAN ID
703 */
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000704 private void addFilterToDevice(DeviceId deviceId, PortNumber port, VlanId assignedVlan, IpAddress mcastIp) {
Charles Chanc91c8782016-03-30 17:54:24 -0700705 // Do nothing if the port is configured as suppressed
Charles Chan370a65b2016-05-10 17:29:47 -0700706 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
707 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +0100708 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Charles Chan370a65b2016-05-10 17:29:47 -0700709 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
710 log.info("Ignore suppressed port {}", connectPoint);
Charles Chanc91c8782016-03-30 17:54:24 -0700711 return;
712 }
713
Charles Chanf909e5b2018-03-02 13:26:22 -0800714 MacAddress routerMac;
715 try {
716 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
717 } catch (DeviceConfigNotFoundException dcnfe) {
718 log.warn("Fail to push filtering objective since device is not configured. Abort");
719 return;
720 }
721
Charles Chanc91c8782016-03-30 17:54:24 -0700722 FilteringObjective.Builder filtObjBuilder =
Charles Chanf909e5b2018-03-02 13:26:22 -0800723 filterObjBuilder(deviceId, port, assignedVlan, mcastIp, routerMac);
Charles Chan72779502016-04-23 17:36:10 -0700724 ObjectiveContext context = new DefaultObjectiveContext(
725 (objective) -> log.debug("Successfully add filter on {}/{}, vlan {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800726 deviceId, port.toLong(), assignedVlan),
Charles Chan72779502016-04-23 17:36:10 -0700727 (objective, error) ->
728 log.warn("Failed to add filter on {}/{}, vlan {}: {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800729 deviceId, port.toLong(), assignedVlan, error));
Charles Chan72779502016-04-23 17:36:10 -0700730 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.add(context));
Charles Chanc91c8782016-03-30 17:54:24 -0700731 }
732
733 /**
734 * Adds a port to given multicast group on given device. This involves the
735 * update of L3 multicast group and multicast routing table entry.
736 *
737 * @param deviceId device ID
738 * @param port port to be added
739 * @param mcastIp multicast group
740 * @param assignedVlan assigned VLAN ID
741 */
742 private void addPortToDevice(DeviceId deviceId, PortNumber port,
743 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700744 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700745 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Pier Luigi4f0dd212018-01-19 10:24:53 +0100746 NextObjective newNextObj;
Charles Chan72779502016-04-23 17:36:10 -0700747 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700748 // First time someone request this mcast group via this device
749 portBuilder.add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100750 // New nextObj
751 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
752 portBuilder.build(), null).add();
753 // Store the new port
754 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700755 } else {
756 // This device already serves some subscribers of this mcast group
Charles Chan72779502016-04-23 17:36:10 -0700757 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700758 // Stop if the port is already in the nextobj
759 Set<PortNumber> existingPorts = getPorts(nextObj.next());
760 if (existingPorts.contains(port)) {
761 log.info("NextObj for {}/{} already exists. Abort", deviceId, port);
762 return;
763 }
Pier Luigi4f0dd212018-01-19 10:24:53 +0100764 // Let's add the port and reuse the previous one
Yuta HIGUCHIbef07b52018-02-09 18:05:23 -0800765 portBuilder.addAll(existingPorts).add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100766 // Reuse previous nextObj
767 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
768 portBuilder.build(), nextObj.id()).addToExisting();
769 // Store the final next objective and send only the difference to the driver
770 mcastNextObjStore.put(mcastStoreKey, newNextObj);
771 // Add just the new port
772 portBuilder = ImmutableSet.builder();
773 portBuilder.add(port);
774 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
775 portBuilder.build(), nextObj.id()).addToExisting();
Charles Chanc91c8782016-03-30 17:54:24 -0700776 }
777 // Create, store and apply the new nextObj and fwdObj
Charles Chan72779502016-04-23 17:36:10 -0700778 ObjectiveContext context = new DefaultObjectiveContext(
779 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
780 mcastIp, deviceId, port.toLong(), assignedVlan),
781 (objective, error) ->
782 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
783 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Charles Chanc91c8782016-03-30 17:54:24 -0700784 ForwardingObjective fwdObj =
Charles Chan72779502016-04-23 17:36:10 -0700785 fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chanc91c8782016-03-30 17:54:24 -0700786 srManager.flowObjectiveService.next(deviceId, newNextObj);
787 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700788 }
789
790 /**
791 * Removes a port from given multicast group on given device.
792 * This involves the update of L3 multicast group and multicast routing
793 * table entry.
794 *
795 * @param deviceId device ID
796 * @param port port to be added
797 * @param mcastIp multicast group
798 * @param assignedVlan assigned VLAN ID
799 * @return true if this is the last sink on this device
800 */
801 private boolean removePortFromDevice(DeviceId deviceId, PortNumber port,
802 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700803 McastStoreKey mcastStoreKey =
804 new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700805 // This device is not serving this multicast group
Charles Chan72779502016-04-23 17:36:10 -0700806 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700807 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
808 return false;
809 }
Charles Chan72779502016-04-23 17:36:10 -0700810 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700811
812 Set<PortNumber> existingPorts = getPorts(nextObj.next());
Charles Chan72779502016-04-23 17:36:10 -0700813 // This port does not serve this multicast group
Charles Chanc91c8782016-03-30 17:54:24 -0700814 if (!existingPorts.contains(port)) {
815 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
816 return false;
817 }
818 // Copy and modify the ImmutableSet
819 existingPorts = Sets.newHashSet(existingPorts);
820 existingPorts.remove(port);
821
822 NextObjective newNextObj;
Pier Luigi8cd46de2018-01-19 10:24:53 +0100823 ObjectiveContext context;
Charles Chanc91c8782016-03-30 17:54:24 -0700824 ForwardingObjective fwdObj;
825 if (existingPorts.isEmpty()) {
Pier Luigi8cd46de2018-01-19 10:24:53 +0100826 // If this is the last sink, remove flows and last bucket
Charles Chanc91c8782016-03-30 17:54:24 -0700827 // NOTE: Rely on GroupStore garbage collection rather than explicitly
828 // remove L3MG since there might be other flows/groups refer to
829 // the same L2IG
Pier Luigi8cd46de2018-01-19 10:24:53 +0100830 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700831 (objective) -> log.debug("Successfully remove {} on {}/{}, vlan {}",
832 mcastIp, deviceId, port.toLong(), assignedVlan),
833 (objective, error) ->
834 log.warn("Failed to remove {} on {}/{}, vlan {}: {}",
835 mcastIp, deviceId, port.toLong(), assignedVlan, error));
836 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
837 mcastNextObjStore.remove(mcastStoreKey);
Charles Chanc91c8782016-03-30 17:54:24 -0700838 } else {
839 // If this is not the last sink, update flows and groups
Pier Luigi8cd46de2018-01-19 10:24:53 +0100840 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700841 (objective) -> log.debug("Successfully update {} on {}/{}, vlan {}",
842 mcastIp, deviceId, port.toLong(), assignedVlan),
843 (objective, error) ->
844 log.warn("Failed to update {} on {}/{}, vlan {}: {}",
845 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier Luigi8cd46de2018-01-19 10:24:53 +0100846 // Here we store the next objective with the remaining port
847 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
848 existingPorts, nextObj.id()).removeFromExisting();
Charles Chan82f19972016-05-17 13:13:55 -0700849 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chan72779502016-04-23 17:36:10 -0700850 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700851 }
Pier Luigi8cd46de2018-01-19 10:24:53 +0100852 // Let's modify the next objective removing the bucket
853 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
854 ImmutableSet.of(port), nextObj.id()).removeFromExisting();
855 srManager.flowObjectiveService.next(deviceId, newNextObj);
856 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700857 return existingPorts.isEmpty();
858 }
859
Charles Chan72779502016-04-23 17:36:10 -0700860 /**
861 * Removes entire group on given device.
862 *
863 * @param deviceId device ID
864 * @param mcastIp multicast group to be removed
865 * @param assignedVlan assigned VLAN ID
866 */
867 private void removeGroupFromDevice(DeviceId deviceId, IpAddress mcastIp,
868 VlanId assignedVlan) {
869 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
870 // This device is not serving this multicast group
871 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
872 log.warn("{} is not serving {}. Abort.", deviceId, mcastIp);
873 return;
874 }
875 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
876 // NOTE: Rely on GroupStore garbage collection rather than explicitly
877 // remove L3MG since there might be other flows/groups refer to
878 // the same L2IG
879 ObjectiveContext context = new DefaultObjectiveContext(
880 (objective) -> log.debug("Successfully remove {} on {}, vlan {}",
881 mcastIp, deviceId, assignedVlan),
882 (objective, error) ->
883 log.warn("Failed to remove {} on {}, vlan {}: {}",
884 mcastIp, deviceId, assignedVlan, error));
885 ForwardingObjective fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
886 srManager.flowObjectiveService.forward(deviceId, fwdObj);
887 mcastNextObjStore.remove(mcastStoreKey);
888 mcastRoleStore.remove(mcastStoreKey);
889 }
890
Pier Luigi580fd8a2018-01-16 10:47:50 +0100891 private void installPath(IpAddress mcastIp, ConnectPoint source, Path mcastPath) {
892 // Get Links
893 List<Link> links = mcastPath.links();
894 // For each link, modify the next on the source device adding the src port
895 // and a new filter objective on the destination port
896 links.forEach(link -> {
897 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
898 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
899 addFilterToDevice(link.dst().deviceId(), link.dst().port(), assignedVlan(null),
900 mcastIp);
901 });
902 // Setup new transit mcast role
903 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
904 McastRole.TRANSIT);
Charles Chan72779502016-04-23 17:36:10 -0700905 }
906
Charles Chanc91c8782016-03-30 17:54:24 -0700907 /**
908 * Creates a next objective builder for multicast.
909 *
910 * @param mcastIp multicast group
911 * @param assignedVlan assigned VLAN ID
912 * @param outPorts set of output port numbers
913 * @return next objective builder
914 */
915 private NextObjective.Builder nextObjBuilder(IpAddress mcastIp,
Pier Luigi4f0dd212018-01-19 10:24:53 +0100916 VlanId assignedVlan, Set<PortNumber> outPorts, Integer nextId) {
917 // If nextId is null allocate a new one
918 if (nextId == null) {
919 nextId = srManager.flowObjectiveService.allocateNextId();
920 }
Charles Chanc91c8782016-03-30 17:54:24 -0700921
922 TrafficSelector metadata =
923 DefaultTrafficSelector.builder()
924 .matchVlanId(assignedVlan)
925 .matchIPDst(mcastIp.toIpPrefix())
926 .build();
927
928 NextObjective.Builder nextObjBuilder = DefaultNextObjective
929 .builder().withId(nextId)
Pier Luigi69f774d2018-02-28 12:10:50 +0100930 .withType(NextObjective.Type.BROADCAST).fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700931 .withMeta(metadata);
932
933 outPorts.forEach(port -> {
934 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
935 if (egressVlan().equals(VlanId.NONE)) {
936 tBuilder.popVlan();
937 }
938 tBuilder.setOutput(port);
939 nextObjBuilder.addTreatment(tBuilder.build());
940 });
941
942 return nextObjBuilder;
943 }
944
945 /**
946 * Creates a forwarding objective builder for multicast.
947 *
948 * @param mcastIp multicast group
949 * @param assignedVlan assigned VLAN ID
950 * @param nextId next ID of the L3 multicast group
951 * @return forwarding objective builder
952 */
953 private ForwardingObjective.Builder fwdObjBuilder(IpAddress mcastIp,
954 VlanId assignedVlan, int nextId) {
955 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000956 IpPrefix mcastPrefix = mcastIp.toIpPrefix();
957
958 if (mcastIp.isIp4()) {
959 sbuilder.matchEthType(Ethernet.TYPE_IPV4);
960 sbuilder.matchIPDst(mcastPrefix);
961 } else {
962 sbuilder.matchEthType(Ethernet.TYPE_IPV6);
963 sbuilder.matchIPv6Dst(mcastPrefix);
964 }
965
966
Charles Chanc91c8782016-03-30 17:54:24 -0700967 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
968 metabuilder.matchVlanId(assignedVlan);
969
970 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder();
971 fwdBuilder.withSelector(sbuilder.build())
972 .withMeta(metabuilder.build())
973 .nextStep(nextId)
974 .withFlag(ForwardingObjective.Flag.SPECIFIC)
Pier Luigi69f774d2018-02-28 12:10:50 +0100975 .fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700976 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
977 return fwdBuilder;
978 }
979
980 /**
981 * Creates a filtering objective builder for multicast.
982 *
983 * @param deviceId Device ID
984 * @param ingressPort ingress port of the multicast stream
985 * @param assignedVlan assigned VLAN ID
Charles Chanf909e5b2018-03-02 13:26:22 -0800986 * @param routerMac router MAC. This is carried in metadata and used from some switches that
987 * need to put unicast entry before multicast entry in TMAC table.
Charles Chanc91c8782016-03-30 17:54:24 -0700988 * @return filtering objective builder
989 */
990 private FilteringObjective.Builder filterObjBuilder(DeviceId deviceId, PortNumber ingressPort,
Charles Chanf909e5b2018-03-02 13:26:22 -0800991 VlanId assignedVlan, IpAddress mcastIp, MacAddress routerMac) {
Charles Chanc91c8782016-03-30 17:54:24 -0700992 FilteringObjective.Builder filtBuilder = DefaultFilteringObjective.builder();
Charles Chan0932eca2016-06-28 16:50:13 -0700993
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000994 if (mcastIp.isIp4()) {
995 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
996 .addCondition(Criteria.matchEthDstMasked(MacAddress.IPV4_MULTICAST,
997 MacAddress.IPV4_MULTICAST_MASK))
998 .addCondition(Criteria.matchVlanId(egressVlan()))
999 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1000 } else {
1001 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
1002 .addCondition(Criteria.matchEthDstMasked(MacAddress.IPV6_MULTICAST,
1003 MacAddress.IPV6_MULTICAST_MASK))
1004 .addCondition(Criteria.matchVlanId(egressVlan()))
1005 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1006 }
Charles Chan0932eca2016-06-28 16:50:13 -07001007 TrafficTreatment tt = DefaultTrafficTreatment.builder()
Charles Chanf909e5b2018-03-02 13:26:22 -08001008 .pushVlan().setVlanId(assignedVlan)
1009 .setEthDst(routerMac)
1010 .build();
Charles Chan0932eca2016-06-28 16:50:13 -07001011 filtBuilder.withMeta(tt);
1012
Pier Luigi69f774d2018-02-28 12:10:50 +01001013 return filtBuilder.permit().fromApp(srManager.appId());
Charles Chanc91c8782016-03-30 17:54:24 -07001014 }
1015
1016 /**
1017 * Gets output ports information from treatments.
1018 *
1019 * @param treatments collection of traffic treatments
1020 * @return set of output port numbers
1021 */
1022 private Set<PortNumber> getPorts(Collection<TrafficTreatment> treatments) {
1023 ImmutableSet.Builder<PortNumber> builder = ImmutableSet.builder();
1024 treatments.forEach(treatment -> {
1025 treatment.allInstructions().stream()
1026 .filter(instr -> instr instanceof OutputInstruction)
1027 .forEach(instr -> {
1028 builder.add(((OutputInstruction) instr).port());
1029 });
1030 });
1031 return builder.build();
1032 }
1033
Pier Luigi51ee7c02018-02-23 19:57:40 +01001034 // Utility method to verify is a link is a pair-link
1035 private boolean isPairLink(Link link) {
1036 // Take src id, src port, dst id and dst port
1037 final DeviceId srcId = link.src().deviceId();
1038 final PortNumber srcPort = link.src().port();
1039 final DeviceId dstId = link.dst().deviceId();
1040 final PortNumber dstPort = link.dst().port();
1041 // init as true
1042 boolean isPairLink = true;
1043 try {
1044 // If one of this condition is not true; it is not a pair link
Pier Luigi69f774d2018-02-28 12:10:50 +01001045 if (!(srManager.deviceConfiguration().isEdgeDevice(srcId) &&
1046 srManager.deviceConfiguration().isEdgeDevice(dstId) &&
1047 srManager.deviceConfiguration().getPairDeviceId(srcId).equals(dstId) &&
1048 srManager.deviceConfiguration().getPairLocalPort(srcId).equals(srcPort) &&
1049 srManager.deviceConfiguration().getPairLocalPort(dstId).equals(dstPort))) {
Pier Luigi51ee7c02018-02-23 19:57:40 +01001050 isPairLink = false;
1051 }
1052 } catch (DeviceConfigNotFoundException e) {
1053 // Configuration not provided
1054 log.warn("Could not check if the link {} is pairlink "
1055 + "config not yet provided", link);
1056 isPairLink = false;
1057 }
1058 return isPairLink;
1059 }
1060
Charles Chanc91c8782016-03-30 17:54:24 -07001061 /**
1062 * Gets a path from src to dst.
1063 * If a path was allocated before, returns the allocated path.
1064 * Otherwise, randomly pick one from available paths.
1065 *
1066 * @param src source device ID
1067 * @param dst destination device ID
1068 * @param mcastIp multicast group
1069 * @return an optional path from src to dst
1070 */
1071 private Optional<Path> getPath(DeviceId src, DeviceId dst, IpAddress mcastIp) {
Pier Luigid8a15162018-02-15 16:33:08 +01001072 // Takes a snapshot of the topology
1073 final Topology currentTopology = topologyService.currentTopology();
Charles Chanc91c8782016-03-30 17:54:24 -07001074 List<Path> allPaths = Lists.newArrayList(
Pier Luigid8a15162018-02-15 16:33:08 +01001075 topologyService.getPaths(currentTopology, src, dst)
1076 );
Pier Luigi51ee7c02018-02-23 19:57:40 +01001077 // Create list of valid paths
1078 allPaths.removeIf(path -> path.links().stream().anyMatch(this::isPairLink));
1079 // If there are no valid paths, just exit
Charles Chan72779502016-04-23 17:36:10 -07001080 log.debug("{} path(s) found from {} to {}", allPaths.size(), src, dst);
Charles Chanc91c8782016-03-30 17:54:24 -07001081 if (allPaths.isEmpty()) {
Charles Chanc91c8782016-03-30 17:54:24 -07001082 return Optional.empty();
1083 }
1084
Pier Luigi91573e12018-01-23 16:06:38 +01001085 // Create a map index of suitablity-to-list of paths. For example
1086 // a path in the list associated to the index 1 shares only the
1087 // first hop and it is less suitable of a path belonging to the index
1088 // 2 that shares leaf-spine.
1089 Map<Integer, List<Path>> eligiblePaths = Maps.newHashMap();
1090 // Some init steps
1091 int nhop;
1092 McastStoreKey mcastStoreKey;
1093 Link hop;
1094 PortNumber srcPort;
1095 Set<PortNumber> existingPorts;
1096 NextObjective nextObj;
1097 // Iterate over paths looking for eligible paths
1098 for (Path path : allPaths) {
1099 // Unlikely, it will happen...
1100 if (!src.equals(path.links().get(0).src().deviceId())) {
1101 continue;
1102 }
1103 nhop = 0;
1104 // Iterate over the links
1105 while (nhop < path.links().size()) {
1106 // Get the link and verify if a next related
1107 // to the src device exist in the store
1108 hop = path.links().get(nhop);
1109 mcastStoreKey = new McastStoreKey(mcastIp, hop.src().deviceId());
1110 // It does not exist in the store, exit
1111 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1112 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001113 }
Pier Luigi91573e12018-01-23 16:06:38 +01001114 // Get the output ports on the next
1115 nextObj = mcastNextObjStore.get(mcastStoreKey).value();
1116 existingPorts = getPorts(nextObj.next());
1117 // And the src port on the link
1118 srcPort = hop.src().port();
1119 // the src port is not used as output, exit
1120 if (!existingPorts.contains(srcPort)) {
1121 break;
1122 }
1123 nhop++;
1124 }
1125 // n_hop defines the index
1126 if (nhop > 0) {
1127 eligiblePaths.compute(nhop, (index, paths) -> {
1128 paths = paths == null ? Lists.newArrayList() : paths;
1129 paths.add(path);
1130 return paths;
1131 });
Charles Chanc91c8782016-03-30 17:54:24 -07001132 }
1133 }
Pier Luigi91573e12018-01-23 16:06:38 +01001134
1135 // No suitable paths
1136 if (eligiblePaths.isEmpty()) {
1137 log.debug("No eligiblePath(s) found from {} to {}", src, dst);
1138 // Otherwise, randomly pick a path
1139 Collections.shuffle(allPaths);
1140 return allPaths.stream().findFirst();
1141 }
1142
1143 // Let's take the best ones
1144 Integer bestIndex = eligiblePaths.keySet()
1145 .stream()
1146 .sorted(Comparator.reverseOrder())
1147 .findFirst().orElse(null);
1148 List<Path> bestPaths = eligiblePaths.get(bestIndex);
1149 log.debug("{} eligiblePath(s) found from {} to {}",
1150 bestPaths.size(), src, dst);
1151 // randomly pick a path on the highest index
1152 Collections.shuffle(bestPaths);
1153 return bestPaths.stream().findFirst();
Charles Chanc91c8782016-03-30 17:54:24 -07001154 }
1155
1156 /**
Charles Chan72779502016-04-23 17:36:10 -07001157 * Gets device(s) of given role in given multicast group.
1158 *
1159 * @param mcastIp multicast IP
1160 * @param role multicast role
1161 * @return set of device ID or empty set if not found
1162 */
1163 private Set<DeviceId> getDevice(IpAddress mcastIp, McastRole role) {
1164 return mcastRoleStore.entrySet().stream()
1165 .filter(entry -> entry.getKey().mcastIp().equals(mcastIp) &&
1166 entry.getValue().value() == role)
1167 .map(Map.Entry::getKey).map(McastStoreKey::deviceId)
1168 .collect(Collectors.toSet());
1169 }
1170
1171 /**
Charles Chana8f9dee2016-05-16 18:44:13 -07001172 * Gets source connect point of given multicast group.
1173 *
1174 * @param mcastIp multicast IP
1175 * @return source connect point or null if not found
1176 */
1177 private ConnectPoint getSource(IpAddress mcastIp) {
1178 return srManager.multicastRouteService.getRoutes().stream()
1179 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1180 .map(mcastRoute -> srManager.multicastRouteService.fetchSource(mcastRoute))
1181 .findAny().orElse(null);
1182 }
1183
1184 /**
Charles Chan72779502016-04-23 17:36:10 -07001185 * Gets groups which is affected by the link down event.
1186 *
1187 * @param link link going down
1188 * @return a set of multicast IpAddress
1189 */
1190 private Set<IpAddress> getAffectedGroups(Link link) {
1191 DeviceId deviceId = link.src().deviceId();
1192 PortNumber port = link.src().port();
1193 return mcastNextObjStore.entrySet().stream()
1194 .filter(entry -> entry.getKey().deviceId().equals(deviceId) &&
1195 getPorts(entry.getValue().value().next()).contains(port))
1196 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1197 .collect(Collectors.toSet());
1198 }
1199
1200 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001201 * Gets groups which are affected by the device down event.
1202 *
1203 * @param deviceId device going down
1204 * @return a set of multicast IpAddress
1205 */
1206 private Set<IpAddress> getAffectedGroups(DeviceId deviceId) {
1207 return mcastNextObjStore.entrySet().stream()
1208 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
1209 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1210 .collect(Collectors.toSet());
1211 }
1212
1213 /**
Charles Chanc91c8782016-03-30 17:54:24 -07001214 * Gets egress VLAN from McastConfig.
1215 *
1216 * @return egress VLAN or VlanId.NONE if not configured
1217 */
1218 private VlanId egressVlan() {
1219 McastConfig mcastConfig =
1220 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1221 return (mcastConfig != null) ? mcastConfig.egressVlan() : VlanId.NONE;
1222 }
1223
1224 /**
1225 * Gets assigned VLAN according to the value of egress VLAN.
Charles Chana8f9dee2016-05-16 18:44:13 -07001226 * If connect point is specified, try to reuse the assigned VLAN on the connect point.
Charles Chanc91c8782016-03-30 17:54:24 -07001227 *
Charles Chana8f9dee2016-05-16 18:44:13 -07001228 * @param cp connect point; Can be null if not specified
1229 * @return assigned VLAN ID
Charles Chanc91c8782016-03-30 17:54:24 -07001230 */
Charles Chana8f9dee2016-05-16 18:44:13 -07001231 private VlanId assignedVlan(ConnectPoint cp) {
1232 // Use the egressVlan if it is tagged
1233 if (!egressVlan().equals(VlanId.NONE)) {
1234 return egressVlan();
1235 }
1236 // Reuse unicast VLAN if the port has subnet configured
1237 if (cp != null) {
Charles Chanf9759582017-10-20 19:09:16 -07001238 VlanId untaggedVlan = srManager.getInternalVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001239 return (untaggedVlan != null) ? untaggedVlan : INTERNAL_VLAN;
Charles Chana8f9dee2016-05-16 18:44:13 -07001240 }
Charles Chan10b0fb72017-02-02 16:20:42 -08001241 // Use DEFAULT_VLAN if none of the above matches
1242 return SegmentRoutingManager.INTERNAL_VLAN;
Charles Chanc91c8782016-03-30 17:54:24 -07001243 }
Charles Chan72779502016-04-23 17:36:10 -07001244
1245 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +01001246 * Gets assigned VLAN according to the value in the meta.
1247 *
1248 * @param nextObjective nextObjective to analyze
1249 * @return assigned VLAN ID
1250 */
1251 private VlanId assignedVlanFromNext(NextObjective nextObjective) {
1252 return ((VlanIdCriterion) nextObjective.meta().getCriterion(VLAN_VID)).vlanId();
1253 }
1254
1255 /**
Charles Chan72779502016-04-23 17:36:10 -07001256 * Gets the spine-facing port on ingress device of given multicast group.
1257 *
1258 * @param mcastIp multicast IP
1259 * @return spine-facing port on ingress device
1260 */
1261 private PortNumber ingressTransitPort(IpAddress mcastIp) {
1262 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
1263 .stream().findAny().orElse(null);
1264 if (ingressDevice != null) {
1265 NextObjective nextObj = mcastNextObjStore
1266 .get(new McastStoreKey(mcastIp, ingressDevice)).value();
1267 Set<PortNumber> ports = getPorts(nextObj.next());
1268
1269 for (PortNumber port : ports) {
1270 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001271 if (srManager.deviceConfiguration() != null &&
1272 srManager.deviceConfiguration().getPortSubnets(ingressDevice, port).isEmpty() &&
Charles Chan82f19972016-05-17 13:13:55 -07001273 !srManager.xConnectHandler.hasXConnect(new ConnectPoint(ingressDevice, port))) {
Charles Chan72779502016-04-23 17:36:10 -07001274 return port;
1275 }
1276 }
1277 }
1278 return null;
1279 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001280
1281 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001282 * Verify if the given device has sinks
1283 * for the multicast group.
1284 *
1285 * @param deviceId device Id
1286 * @param mcastIp multicast IP
1287 * @return true if the device has sink for the group.
1288 * False otherwise.
1289 */
1290 private boolean hasSinks(DeviceId deviceId, IpAddress mcastIp) {
1291 if (deviceId != null) {
1292 // Get the nextobjective
1293 Versioned<NextObjective> versionedNextObj = mcastNextObjStore.get(
1294 new McastStoreKey(mcastIp, deviceId)
1295 );
1296 // If it exists
1297 if (versionedNextObj != null) {
1298 NextObjective nextObj = versionedNextObj.value();
1299 // Retrieves all the output ports
1300 Set<PortNumber> ports = getPorts(nextObj.next());
1301 // Tries to find at least one port that is not spine-facing
1302 for (PortNumber port : ports) {
1303 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001304 if (srManager.deviceConfiguration() != null &&
1305 (!srManager.deviceConfiguration().getPortSubnets(deviceId, port).isEmpty() ||
Pier Luigi580fd8a2018-01-16 10:47:50 +01001306 srManager.xConnectHandler.hasXConnect(new ConnectPoint(deviceId, port)))) {
1307 return true;
1308 }
1309 }
1310 }
1311 }
1312 return false;
1313 }
1314
1315 /**
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001316 * Removes filtering objective for given device and port.
1317 *
1318 * @param deviceId device ID
1319 * @param port ingress port number
1320 * @param assignedVlan assigned VLAN ID
1321 * @param mcastIp multicast IP address
1322 */
1323 private void removeFilterToDevice(DeviceId deviceId, PortNumber port, VlanId assignedVlan, IpAddress mcastIp) {
1324 // Do nothing if the port is configured as suppressed
1325 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
1326 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +01001327 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001328 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
1329 log.info("Ignore suppressed port {}", connectPoint);
1330 return;
1331 }
1332
Charles Chanf909e5b2018-03-02 13:26:22 -08001333 MacAddress routerMac;
1334 try {
1335 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
1336 } catch (DeviceConfigNotFoundException dcnfe) {
1337 log.warn("Fail to push filtering objective since device is not configured. Abort");
1338 return;
1339 }
1340
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001341 FilteringObjective.Builder filtObjBuilder =
Charles Chanf909e5b2018-03-02 13:26:22 -08001342 filterObjBuilder(deviceId, port, assignedVlan, mcastIp, routerMac);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001343 ObjectiveContext context = new DefaultObjectiveContext(
1344 (objective) -> log.debug("Successfully removed filter on {}/{}, vlan {}",
1345 deviceId, port.toLong(), assignedVlan),
1346 (objective, error) ->
1347 log.warn("Failed to remove filter on {}/{}, vlan {}: {}",
1348 deviceId, port.toLong(), assignedVlan, error));
1349 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.remove(context));
1350 }
1351
1352 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +01001353 * Updates filtering objective for given device and port.
1354 * It is called in general when the mcast config has been
1355 * changed.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001356 *
1357 * @param deviceId device ID
1358 * @param portNum ingress port number
1359 * @param vlanId assigned VLAN ID
1360 * @param install true to add, false to remove
1361 */
Pier Luigi69f774d2018-02-28 12:10:50 +01001362 public void updateFilterToDevice(DeviceId deviceId, PortNumber portNum,
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001363 VlanId vlanId, boolean install) {
Pier Luigi35dab3f2018-01-25 16:16:02 +01001364 lastMcastChange = Instant.now();
1365 mcastLock();
1366 try {
1367 // Iterates over the route and updates properly the filtering objective
1368 // on the source device.
1369 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
1370 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
1371 if (source.deviceId().equals(deviceId) && source.port().equals(portNum)) {
1372 if (install) {
1373 addFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group());
1374 } else {
1375 removeFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group());
1376 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001377 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001378 });
1379 } finally {
1380 mcastUnlock();
1381 }
1382 }
1383
Pier Luigi6786b922018-02-02 16:19:11 +01001384 private boolean isLeader(ConnectPoint source) {
1385 // Continue only when we have the mastership on the operation
1386 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1387 // When the source is available we just check the mastership
1388 if (srManager.deviceService.isAvailable(source.deviceId())) {
1389 return false;
1390 }
1391 // Fallback with Leadership service
1392 // source id is used a topic
1393 NodeId leader = srManager.leadershipService.runForLeadership(
1394 source.deviceId().toString()).leaderNodeId();
1395 // Verify if this node is the leader
1396 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1397 return false;
1398 }
1399 }
1400 // Done
1401 return true;
1402 }
1403
Pier Luigi35dab3f2018-01-25 16:16:02 +01001404 /**
1405 * Performs bucket verification operation for all mcast groups in the devices.
1406 * Firstly, it verifies that mcast is stable before trying verification operation.
1407 * Verification consists in creating new nexts with VERIFY operation. Actually,
1408 * the operation is totally delegated to the driver.
1409 */
1410 private final class McastBucketCorrector implements Runnable {
1411
1412 @Override
1413 public void run() {
1414 // Verify if the Mcast has been stable for MCAST_STABLITY_THRESHOLD
1415 if (!isMcastStable()) {
1416 return;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001417 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001418 // Acquires lock
1419 mcastLock();
1420 try {
1421 // Iterates over the routes and verify the related next objectives
1422 srManager.multicastRouteService.getRoutes()
1423 .stream()
1424 .map(McastRoute::group)
1425 .forEach(mcastIp -> {
1426 log.trace("Running mcast buckets corrector for mcast group: {}",
1427 mcastIp);
1428
1429 // For each group we get current information in the store
1430 // and issue a check of the next objectives in place
1431 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
1432 .stream().findAny().orElse(null);
1433 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
1434 .stream().findAny().orElse(null);
1435 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
1436 ConnectPoint source = getSource(mcastIp);
1437
1438 // Do not proceed if ingress device or source of this group are missing
1439 if (ingressDevice == null || source == null) {
1440 log.warn("Unable to run buckets corrector. " +
1441 "Missing ingress {} or source {} for group {}",
1442 ingressDevice, source, mcastIp);
1443 return;
1444 }
1445
1446 // Continue only when this instance is the master of source device
1447 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1448 log.trace("Unable to run buckets corrector. " +
1449 "Skip {} due to lack of mastership " +
1450 "of the source device {}",
1451 mcastIp, source.deviceId());
1452 return;
1453 }
1454
1455 // Create the set of the devices to be processed
1456 ImmutableSet.Builder<DeviceId> devicesBuilder = ImmutableSet.builder();
1457 devicesBuilder.add(ingressDevice);
1458 if (transitDevice != null) {
1459 devicesBuilder.add(transitDevice);
1460 }
1461 if (!egressDevices.isEmpty()) {
1462 devicesBuilder.addAll(egressDevices);
1463 }
1464 Set<DeviceId> devicesToProcess = devicesBuilder.build();
1465
1466 // Iterate over the devices
1467 devicesToProcess.forEach(deviceId -> {
1468 McastStoreKey currentKey = new McastStoreKey(mcastIp, deviceId);
1469 // If next exists in our store verify related next objective
1470 if (mcastNextObjStore.containsKey(currentKey)) {
1471 NextObjective currentNext = mcastNextObjStore.get(currentKey).value();
1472 // Get current ports
1473 Set<PortNumber> currentPorts = getPorts(currentNext.next());
1474 // Rebuild the next objective
1475 currentNext = nextObjBuilder(
1476 mcastIp,
1477 assignedVlan(deviceId.equals(source.deviceId()) ? source : null),
1478 currentPorts,
1479 currentNext.id()
1480 ).verify();
1481 // Send to the flowobjective service
1482 srManager.flowObjectiveService.next(deviceId, currentNext);
1483 } else {
Pier Luigid8a15162018-02-15 16:33:08 +01001484 log.warn("Unable to run buckets corrector. " +
Pier Luigi35dab3f2018-01-25 16:16:02 +01001485 "Missing next for {} and group {}",
1486 deviceId, mcastIp);
1487 }
1488 });
1489
1490 });
1491 } finally {
1492 // Finally, it releases the lock
1493 mcastUnlock();
1494 }
1495
1496 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001497 }
Pier Luigi0f9635b2018-01-15 18:06:43 +01001498
1499 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
1500 // If mcast ip is present
1501 if (mcastIp != null) {
1502 return mcastNextObjStore.entrySet().stream()
1503 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1504 .collect(Collectors.toMap(Map.Entry::getKey,
1505 entry -> entry.getValue().value().id()));
1506 }
1507 // Otherwise take all the groups
1508 return mcastNextObjStore.entrySet().stream()
1509 .collect(Collectors.toMap(Map.Entry::getKey,
1510 entry -> entry.getValue().value().id()));
1511 }
1512
Pier Luigi69f774d2018-02-28 12:10:50 +01001513 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +01001514 // If mcast ip is present
1515 if (mcastIp != null) {
1516 return mcastRoleStore.entrySet().stream()
1517 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1518 .collect(Collectors.toMap(Map.Entry::getKey,
1519 entry -> entry.getValue().value()));
1520 }
1521 // Otherwise take all the groups
1522 return mcastRoleStore.entrySet().stream()
1523 .collect(Collectors.toMap(Map.Entry::getKey,
1524 entry -> entry.getValue().value()));
1525 }
1526
1527 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
1528 Map<ConnectPoint, List<ConnectPoint>> mcastPaths = Maps.newHashMap();
1529 // Get the source
1530 ConnectPoint source = getSource(mcastIp);
1531 // Source cannot be null, we don't know the starting point
1532 if (source != null) {
1533 // Init steps
1534 Set<DeviceId> visited = Sets.newHashSet();
1535 List<ConnectPoint> currentPath = Lists.newArrayList(
1536 source
1537 );
1538 // Build recursively the mcast paths
1539 buildMcastPaths(source.deviceId(), visited, mcastPaths, currentPath, mcastIp);
1540 }
1541 return mcastPaths;
1542 }
1543
1544 private void buildMcastPaths(DeviceId toVisit, Set<DeviceId> visited,
1545 Map<ConnectPoint, List<ConnectPoint>> mcastPaths,
1546 List<ConnectPoint> currentPath, IpAddress mcastIp) {
1547 // If we have visited the node to visit
1548 // there is a loop
1549 if (visited.contains(toVisit)) {
1550 return;
1551 }
1552 // Visit next-hop
1553 visited.add(toVisit);
1554 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, toVisit);
1555 // Looking for next-hops
1556 if (mcastNextObjStore.containsKey(mcastStoreKey)) {
1557 // Build egress connectpoints
1558 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
1559 // Get Ports
1560 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
1561 // Build relative cps
1562 ImmutableSet.Builder<ConnectPoint> cpBuilder = ImmutableSet.builder();
1563 outputPorts.forEach(portNumber -> cpBuilder.add(new ConnectPoint(toVisit, portNumber)));
1564 Set<ConnectPoint> egressPoints = cpBuilder.build();
1565 // Define other variables for the next steps
1566 Set<Link> egressLinks;
1567 List<ConnectPoint> newCurrentPath;
1568 Set<DeviceId> newVisited;
1569 DeviceId newToVisit;
1570 for (ConnectPoint egressPoint : egressPoints) {
1571 egressLinks = srManager.linkService.getEgressLinks(egressPoint);
1572 // If it does not have egress links, stop
1573 if (egressLinks.isEmpty()) {
1574 // Add the connect points to the path
1575 newCurrentPath = Lists.newArrayList(currentPath);
1576 newCurrentPath.add(0, egressPoint);
1577 // Save in the map
1578 mcastPaths.put(egressPoint, newCurrentPath);
1579 } else {
1580 newVisited = Sets.newHashSet(visited);
1581 // Iterate over the egress links for the next hops
1582 for (Link egressLink : egressLinks) {
1583 // Update to visit
1584 newToVisit = egressLink.dst().deviceId();
1585 // Add the connect points to the path
1586 newCurrentPath = Lists.newArrayList(currentPath);
1587 newCurrentPath.add(0, egressPoint);
1588 newCurrentPath.add(0, egressLink.dst());
1589 // Go to the next hop
1590 buildMcastPaths(newToVisit, newVisited, mcastPaths, newCurrentPath, mcastIp);
1591 }
1592 }
1593 }
1594 }
1595 }
1596
Charles Chanc91c8782016-03-30 17:54:24 -07001597}