blob: 3cab53bb8aad8bf8f0d3d6f7fa28fefc302f09b3 [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 Luigi92e69be2018-03-02 12:53:37 +0100428 boolean isLast = false;
Pier Luigi35dab3f2018-01-25 16:16:02 +0100429 // When source and sink are on the same device
430 if (source.deviceId().equals(sink.deviceId())) {
431 // Source and sink are on even the same port. There must be something wrong.
432 if (source.port().equals(sink.port())) {
433 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
434 mcastIp, sink, source);
435 return;
436 }
Pier Luigi92e69be2018-03-02 12:53:37 +0100437 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
438 if (isLast) {
439 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
440 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100441 return;
442 }
Charles Chanc91c8782016-03-30 17:54:24 -0700443
Pier Luigi35dab3f2018-01-25 16:16:02 +0100444 // Process the egress device
Pier Luigi92e69be2018-03-02 12:53:37 +0100445 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100446 if (isLast) {
447 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
448 }
449
450 // If this is the last sink on the device, also update upstream
451 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
452 if (mcastPath.isPresent()) {
453 List<Link> links = Lists.newArrayList(mcastPath.get().links());
454 Collections.reverse(links);
455 for (Link link : links) {
456 if (isLast) {
457 isLast = removePortFromDevice(
458 link.src().deviceId(),
459 link.src().port(),
460 mcastIp,
461 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null)
462 );
Pier Luigi92e69be2018-03-02 12:53:37 +0100463 if (isLast) {
464 mcastRoleStore.remove(new McastStoreKey(mcastIp, link.src().deviceId()));
465 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100466 }
Charles Chanc91c8782016-03-30 17:54:24 -0700467 }
468 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100469 } finally {
470 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700471 }
472 }
473
474 /**
475 * Establishes a path from source to sink for given multicast group.
476 *
477 * @param source connect point of the multicast source
478 * @param sink connection point of the multicast sink
479 * @param mcastIp multicast group IP address
480 */
481 private void processSinkAddedInternal(ConnectPoint source, ConnectPoint sink,
482 IpAddress mcastIp) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100483 lastMcastChange = Instant.now();
484 mcastLock();
485 try {
486 // Continue only when this instance is the master of source device
487 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
488 log.debug("Skip {} due to lack of mastership of the source device {}",
489 mcastIp, source.deviceId());
Charles Chanc91c8782016-03-30 17:54:24 -0700490 return;
491 }
Charles Chanc91c8782016-03-30 17:54:24 -0700492
Pier Luigi35dab3f2018-01-25 16:16:02 +0100493 // Process the ingress device
494 addFilterToDevice(source.deviceId(), source.port(), assignedVlan(source), mcastIp);
Charles Chan72779502016-04-23 17:36:10 -0700495
Pier Luigi35dab3f2018-01-25 16:16:02 +0100496 // When source and sink are on the same device
497 if (source.deviceId().equals(sink.deviceId())) {
498 // Source and sink are on even the same port. There must be something wrong.
499 if (source.port().equals(sink.port())) {
500 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
501 mcastIp, sink, source);
502 return;
503 }
504 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
505 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()), McastRole.INGRESS);
506 return;
507 }
Charles Chan72779502016-04-23 17:36:10 -0700508
Pier Luigi35dab3f2018-01-25 16:16:02 +0100509 // Find a path. If present, create/update groups and flows for each hop
510 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
511 if (mcastPath.isPresent()) {
512 List<Link> links = mcastPath.get().links();
513 checkState(links.size() == 2,
514 "Path in leaf-spine topology should always be two hops: ", links);
Charles Chan72779502016-04-23 17:36:10 -0700515
Pier Luigi35dab3f2018-01-25 16:16:02 +0100516 links.forEach(link -> {
517 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
518 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
519 addFilterToDevice(link.dst().deviceId(), link.dst().port(), assignedVlan(null), mcastIp);
520 });
521
522 // Process the egress device
523 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
524
525 // Setup mcast roles
526 mcastRoleStore.put(new McastStoreKey(mcastIp, source.deviceId()),
527 McastRole.INGRESS);
528 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
529 McastRole.TRANSIT);
530 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()),
531 McastRole.EGRESS);
532 } else {
533 log.warn("Unable to find a path from {} to {}. Abort sinkAdded",
534 source.deviceId(), sink.deviceId());
535 }
536 } finally {
537 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700538 }
539 }
540
541 /**
Charles Chan72779502016-04-23 17:36:10 -0700542 * Processes the LINK_DOWN event.
543 *
544 * @param affectedLink Link that is going down
545 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100546 public void processLinkDown(Link affectedLink) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100547 lastMcastChange = Instant.now();
548 mcastLock();
549 try {
550 // Get groups affected by the link down event
551 getAffectedGroups(affectedLink).forEach(mcastIp -> {
552 // TODO Optimize when the group editing is in place
553 log.debug("Processing link down {} for group {}",
554 affectedLink, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100555
Pier Luigi35dab3f2018-01-25 16:16:02 +0100556 // Find out the ingress, transit and egress device of affected group
557 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
558 .stream().findAny().orElse(null);
559 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
560 .stream().findAny().orElse(null);
561 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
562 ConnectPoint source = getSource(mcastIp);
Charles Chana8f9dee2016-05-16 18:44:13 -0700563
Pier Luigi35dab3f2018-01-25 16:16:02 +0100564 // Do not proceed if any of these info is missing
565 if (ingressDevice == null || transitDevice == null
566 || egressDevices == null || source == null) {
567 log.warn("Missing ingress {}, transit {}, egress {} devices or source {}",
568 ingressDevice, transitDevice, egressDevices, source);
569 return;
Charles Chan72779502016-04-23 17:36:10 -0700570 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100571
572 // Continue only when this instance is the master of source device
573 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
574 log.debug("Skip {} due to lack of mastership of the source device {}",
575 source.deviceId());
576 return;
577 }
578
579 // Remove entire transit
580 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
581
582 // Remove transit-facing port on ingress device
583 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
584 if (ingressTransitPort != null) {
Pier Luigi92e69be2018-03-02 12:53:37 +0100585 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
586 mcastIp, assignedVlan(source));
587 if (isLast) {
588 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
589 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100590 }
591
592 // Construct a new path for each egress device
593 egressDevices.forEach(egressDevice -> {
594 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
595 if (mcastPath.isPresent()) {
596 installPath(mcastIp, source, mcastPath.get());
597 } else {
598 log.warn("Fail to recover egress device {} from link failure {}",
599 egressDevice, affectedLink);
600 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
601 }
602 });
Charles Chan72779502016-04-23 17:36:10 -0700603 });
Pier Luigi35dab3f2018-01-25 16:16:02 +0100604 } finally {
605 mcastUnlock();
606 }
Charles Chan72779502016-04-23 17:36:10 -0700607 }
608
609 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +0100610 * Process the DEVICE_DOWN event.
611 *
612 * @param deviceDown device going down
613 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100614 public void processDeviceDown(DeviceId deviceDown) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100615 lastMcastChange = Instant.now();
616 mcastLock();
617 try {
618 // Get the mcast groups affected by the device going down
619 getAffectedGroups(deviceDown).forEach(mcastIp -> {
620 // TODO Optimize when the group editing is in place
621 log.debug("Processing device down {} for group {}",
622 deviceDown, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100623
Pier Luigi35dab3f2018-01-25 16:16:02 +0100624 // Find out the ingress, transit and egress device of affected group
625 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
626 .stream().findAny().orElse(null);
627 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
628 .stream().findAny().orElse(null);
629 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
630 ConnectPoint source = getSource(mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100631
Pier Luigi35dab3f2018-01-25 16:16:02 +0100632 // Do not proceed if ingress device or source of this group are missing
633 // If sinks are in other leafs, we have ingress, transit, egress, and source
634 // If sinks are in the same leaf, we have just ingress and source
635 if (ingressDevice == null || source == null) {
636 log.warn("Missing ingress {} or source {} for group {}",
637 ingressDevice, source, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100638 return;
639 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100640
Pier Luigi6786b922018-02-02 16:19:11 +0100641 // Verify leadership on the operation
642 if (!isLeader(source)) {
643 log.debug("Skip {} due to lack of leadership", mcastIp);
644 return;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100645 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100646
647 // If it exists, we have to remove it in any case
648 if (transitDevice != null) {
649 // Remove entire transit
650 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
651 }
652 // If the ingress is down
653 if (ingressDevice.equals(deviceDown)) {
654 // Remove entire ingress
655 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
656 // If other sinks different from the ingress exist
657 if (!egressDevices.isEmpty()) {
658 // Remove all the remaining egress
659 egressDevices.forEach(
660 egressDevice -> removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null))
661 );
Pier Luigi580fd8a2018-01-16 10:47:50 +0100662 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100663 } else {
664 // Egress or transit could be down at this point
665 // Get the ingress-transit port if it exists
666 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
667 if (ingressTransitPort != null) {
668 // Remove transit-facing port on ingress device
Pier Luigi92e69be2018-03-02 12:53:37 +0100669 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
670 mcastIp, assignedVlan(source));
671 // There are no further ports
672 if (isLast) {
673 // Remove entire ingress
674 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
675 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100676 }
677 // One of the egress device is down
678 if (egressDevices.contains(deviceDown)) {
679 // Remove entire device down
680 removeGroupFromDevice(deviceDown, mcastIp, assignedVlan(null));
681 // Remove the device down from egress
682 egressDevices.remove(deviceDown);
683 // If there are no more egress and ingress does not have sinks
684 if (egressDevices.isEmpty() && !hasSinks(ingressDevice, mcastIp)) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100685 // We have done
686 return;
687 }
688 }
689 // Construct a new path for each egress device
690 egressDevices.forEach(egressDevice -> {
691 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
692 // If there is a new path
693 if (mcastPath.isPresent()) {
694 // Let's install the new mcast path for this egress
695 installPath(mcastIp, source, mcastPath.get());
696 } else {
697 // We were not able to find an alternative path for this egress
698 log.warn("Fail to recover egress device {} from device down {}",
699 egressDevice, deviceDown);
700 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
701 }
702 });
703 }
704 });
705 } finally {
706 mcastUnlock();
707 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100708 }
709
710 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700711 * Adds filtering objective for given device and port.
712 *
713 * @param deviceId device ID
714 * @param port ingress port number
715 * @param assignedVlan assigned VLAN ID
716 */
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000717 private void addFilterToDevice(DeviceId deviceId, PortNumber port, VlanId assignedVlan, IpAddress mcastIp) {
Charles Chanc91c8782016-03-30 17:54:24 -0700718 // Do nothing if the port is configured as suppressed
Charles Chan370a65b2016-05-10 17:29:47 -0700719 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
720 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +0100721 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Charles Chan370a65b2016-05-10 17:29:47 -0700722 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
723 log.info("Ignore suppressed port {}", connectPoint);
Charles Chanc91c8782016-03-30 17:54:24 -0700724 return;
725 }
726
Charles Chanf909e5b2018-03-02 13:26:22 -0800727 MacAddress routerMac;
728 try {
729 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
730 } catch (DeviceConfigNotFoundException dcnfe) {
731 log.warn("Fail to push filtering objective since device is not configured. Abort");
732 return;
733 }
734
Charles Chanc91c8782016-03-30 17:54:24 -0700735 FilteringObjective.Builder filtObjBuilder =
Charles Chanf909e5b2018-03-02 13:26:22 -0800736 filterObjBuilder(deviceId, port, assignedVlan, mcastIp, routerMac);
Charles Chan72779502016-04-23 17:36:10 -0700737 ObjectiveContext context = new DefaultObjectiveContext(
738 (objective) -> log.debug("Successfully add filter on {}/{}, vlan {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800739 deviceId, port.toLong(), assignedVlan),
Charles Chan72779502016-04-23 17:36:10 -0700740 (objective, error) ->
741 log.warn("Failed to add filter on {}/{}, vlan {}: {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800742 deviceId, port.toLong(), assignedVlan, error));
Charles Chan72779502016-04-23 17:36:10 -0700743 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.add(context));
Charles Chanc91c8782016-03-30 17:54:24 -0700744 }
745
746 /**
747 * Adds a port to given multicast group on given device. This involves the
748 * update of L3 multicast group and multicast routing table entry.
749 *
750 * @param deviceId device ID
751 * @param port port to be added
752 * @param mcastIp multicast group
753 * @param assignedVlan assigned VLAN ID
754 */
755 private void addPortToDevice(DeviceId deviceId, PortNumber port,
756 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700757 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700758 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Pier Luigi4f0dd212018-01-19 10:24:53 +0100759 NextObjective newNextObj;
Charles Chan72779502016-04-23 17:36:10 -0700760 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700761 // First time someone request this mcast group via this device
762 portBuilder.add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100763 // New nextObj
764 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
765 portBuilder.build(), null).add();
766 // Store the new port
767 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700768 } else {
769 // This device already serves some subscribers of this mcast group
Charles Chan72779502016-04-23 17:36:10 -0700770 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700771 // Stop if the port is already in the nextobj
772 Set<PortNumber> existingPorts = getPorts(nextObj.next());
773 if (existingPorts.contains(port)) {
774 log.info("NextObj for {}/{} already exists. Abort", deviceId, port);
775 return;
776 }
Pier Luigi4f0dd212018-01-19 10:24:53 +0100777 // Let's add the port and reuse the previous one
Yuta HIGUCHIbef07b52018-02-09 18:05:23 -0800778 portBuilder.addAll(existingPorts).add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100779 // Reuse previous nextObj
780 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
781 portBuilder.build(), nextObj.id()).addToExisting();
782 // Store the final next objective and send only the difference to the driver
783 mcastNextObjStore.put(mcastStoreKey, newNextObj);
784 // Add just the new port
785 portBuilder = ImmutableSet.builder();
786 portBuilder.add(port);
787 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
788 portBuilder.build(), nextObj.id()).addToExisting();
Charles Chanc91c8782016-03-30 17:54:24 -0700789 }
790 // Create, store and apply the new nextObj and fwdObj
Charles Chan72779502016-04-23 17:36:10 -0700791 ObjectiveContext context = new DefaultObjectiveContext(
792 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
793 mcastIp, deviceId, port.toLong(), assignedVlan),
794 (objective, error) ->
795 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
796 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Charles Chanc91c8782016-03-30 17:54:24 -0700797 ForwardingObjective fwdObj =
Charles Chan72779502016-04-23 17:36:10 -0700798 fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chanc91c8782016-03-30 17:54:24 -0700799 srManager.flowObjectiveService.next(deviceId, newNextObj);
800 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700801 }
802
803 /**
804 * Removes a port from given multicast group on given device.
805 * This involves the update of L3 multicast group and multicast routing
806 * table entry.
807 *
808 * @param deviceId device ID
809 * @param port port to be added
810 * @param mcastIp multicast group
811 * @param assignedVlan assigned VLAN ID
812 * @return true if this is the last sink on this device
813 */
814 private boolean removePortFromDevice(DeviceId deviceId, PortNumber port,
815 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700816 McastStoreKey mcastStoreKey =
817 new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700818 // This device is not serving this multicast group
Charles Chan72779502016-04-23 17:36:10 -0700819 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700820 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
821 return false;
822 }
Charles Chan72779502016-04-23 17:36:10 -0700823 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700824
825 Set<PortNumber> existingPorts = getPorts(nextObj.next());
Charles Chan72779502016-04-23 17:36:10 -0700826 // This port does not serve this multicast group
Charles Chanc91c8782016-03-30 17:54:24 -0700827 if (!existingPorts.contains(port)) {
828 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
829 return false;
830 }
831 // Copy and modify the ImmutableSet
832 existingPorts = Sets.newHashSet(existingPorts);
833 existingPorts.remove(port);
834
835 NextObjective newNextObj;
Pier Luigi8cd46de2018-01-19 10:24:53 +0100836 ObjectiveContext context;
Charles Chanc91c8782016-03-30 17:54:24 -0700837 ForwardingObjective fwdObj;
838 if (existingPorts.isEmpty()) {
Pier Luigi8cd46de2018-01-19 10:24:53 +0100839 // If this is the last sink, remove flows and last bucket
Charles Chanc91c8782016-03-30 17:54:24 -0700840 // NOTE: Rely on GroupStore garbage collection rather than explicitly
841 // remove L3MG since there might be other flows/groups refer to
842 // the same L2IG
Pier Luigi8cd46de2018-01-19 10:24:53 +0100843 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700844 (objective) -> log.debug("Successfully remove {} on {}/{}, vlan {}",
845 mcastIp, deviceId, port.toLong(), assignedVlan),
846 (objective, error) ->
847 log.warn("Failed to remove {} on {}/{}, vlan {}: {}",
848 mcastIp, deviceId, port.toLong(), assignedVlan, error));
849 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
850 mcastNextObjStore.remove(mcastStoreKey);
Charles Chanc91c8782016-03-30 17:54:24 -0700851 } else {
852 // If this is not the last sink, update flows and groups
Pier Luigi8cd46de2018-01-19 10:24:53 +0100853 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700854 (objective) -> log.debug("Successfully update {} on {}/{}, vlan {}",
855 mcastIp, deviceId, port.toLong(), assignedVlan),
856 (objective, error) ->
857 log.warn("Failed to update {} on {}/{}, vlan {}: {}",
858 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier Luigi8cd46de2018-01-19 10:24:53 +0100859 // Here we store the next objective with the remaining port
860 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
861 existingPorts, nextObj.id()).removeFromExisting();
Charles Chan82f19972016-05-17 13:13:55 -0700862 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chan72779502016-04-23 17:36:10 -0700863 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700864 }
Pier Luigi8cd46de2018-01-19 10:24:53 +0100865 // Let's modify the next objective removing the bucket
866 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
867 ImmutableSet.of(port), nextObj.id()).removeFromExisting();
868 srManager.flowObjectiveService.next(deviceId, newNextObj);
869 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700870 return existingPorts.isEmpty();
871 }
872
Charles Chan72779502016-04-23 17:36:10 -0700873 /**
874 * Removes entire group on given device.
875 *
876 * @param deviceId device ID
877 * @param mcastIp multicast group to be removed
878 * @param assignedVlan assigned VLAN ID
879 */
880 private void removeGroupFromDevice(DeviceId deviceId, IpAddress mcastIp,
881 VlanId assignedVlan) {
882 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
883 // This device is not serving this multicast group
884 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
885 log.warn("{} is not serving {}. Abort.", deviceId, mcastIp);
886 return;
887 }
888 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
889 // NOTE: Rely on GroupStore garbage collection rather than explicitly
890 // remove L3MG since there might be other flows/groups refer to
891 // the same L2IG
892 ObjectiveContext context = new DefaultObjectiveContext(
893 (objective) -> log.debug("Successfully remove {} on {}, vlan {}",
894 mcastIp, deviceId, assignedVlan),
895 (objective, error) ->
896 log.warn("Failed to remove {} on {}, vlan {}: {}",
897 mcastIp, deviceId, assignedVlan, error));
898 ForwardingObjective fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
899 srManager.flowObjectiveService.forward(deviceId, fwdObj);
900 mcastNextObjStore.remove(mcastStoreKey);
901 mcastRoleStore.remove(mcastStoreKey);
902 }
903
Pier Luigi580fd8a2018-01-16 10:47:50 +0100904 private void installPath(IpAddress mcastIp, ConnectPoint source, Path mcastPath) {
905 // Get Links
906 List<Link> links = mcastPath.links();
907 // For each link, modify the next on the source device adding the src port
908 // and a new filter objective on the destination port
909 links.forEach(link -> {
910 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
911 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
912 addFilterToDevice(link.dst().deviceId(), link.dst().port(), assignedVlan(null),
913 mcastIp);
914 });
915 // Setup new transit mcast role
916 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
917 McastRole.TRANSIT);
Pier Luigi92e69be2018-03-02 12:53:37 +0100918 // Setup new ingress mcast role
919 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).src().deviceId()),
920 McastRole.INGRESS);
Charles Chan72779502016-04-23 17:36:10 -0700921 }
922
Charles Chanc91c8782016-03-30 17:54:24 -0700923 /**
924 * Creates a next objective builder for multicast.
925 *
926 * @param mcastIp multicast group
927 * @param assignedVlan assigned VLAN ID
928 * @param outPorts set of output port numbers
929 * @return next objective builder
930 */
931 private NextObjective.Builder nextObjBuilder(IpAddress mcastIp,
Pier Luigi4f0dd212018-01-19 10:24:53 +0100932 VlanId assignedVlan, Set<PortNumber> outPorts, Integer nextId) {
933 // If nextId is null allocate a new one
934 if (nextId == null) {
935 nextId = srManager.flowObjectiveService.allocateNextId();
936 }
Charles Chanc91c8782016-03-30 17:54:24 -0700937
938 TrafficSelector metadata =
939 DefaultTrafficSelector.builder()
940 .matchVlanId(assignedVlan)
941 .matchIPDst(mcastIp.toIpPrefix())
942 .build();
943
944 NextObjective.Builder nextObjBuilder = DefaultNextObjective
945 .builder().withId(nextId)
Pier Luigi69f774d2018-02-28 12:10:50 +0100946 .withType(NextObjective.Type.BROADCAST).fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700947 .withMeta(metadata);
948
949 outPorts.forEach(port -> {
950 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
951 if (egressVlan().equals(VlanId.NONE)) {
952 tBuilder.popVlan();
953 }
954 tBuilder.setOutput(port);
955 nextObjBuilder.addTreatment(tBuilder.build());
956 });
957
958 return nextObjBuilder;
959 }
960
961 /**
962 * Creates a forwarding objective builder for multicast.
963 *
964 * @param mcastIp multicast group
965 * @param assignedVlan assigned VLAN ID
966 * @param nextId next ID of the L3 multicast group
967 * @return forwarding objective builder
968 */
969 private ForwardingObjective.Builder fwdObjBuilder(IpAddress mcastIp,
970 VlanId assignedVlan, int nextId) {
971 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000972 IpPrefix mcastPrefix = mcastIp.toIpPrefix();
973
974 if (mcastIp.isIp4()) {
975 sbuilder.matchEthType(Ethernet.TYPE_IPV4);
976 sbuilder.matchIPDst(mcastPrefix);
977 } else {
978 sbuilder.matchEthType(Ethernet.TYPE_IPV6);
979 sbuilder.matchIPv6Dst(mcastPrefix);
980 }
981
982
Charles Chanc91c8782016-03-30 17:54:24 -0700983 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
984 metabuilder.matchVlanId(assignedVlan);
985
986 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder();
987 fwdBuilder.withSelector(sbuilder.build())
988 .withMeta(metabuilder.build())
989 .nextStep(nextId)
990 .withFlag(ForwardingObjective.Flag.SPECIFIC)
Pier Luigi69f774d2018-02-28 12:10:50 +0100991 .fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700992 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
993 return fwdBuilder;
994 }
995
996 /**
997 * Creates a filtering objective builder for multicast.
998 *
999 * @param deviceId Device ID
1000 * @param ingressPort ingress port of the multicast stream
1001 * @param assignedVlan assigned VLAN ID
Charles Chanf909e5b2018-03-02 13:26:22 -08001002 * @param routerMac router MAC. This is carried in metadata and used from some switches that
1003 * need to put unicast entry before multicast entry in TMAC table.
Charles Chanc91c8782016-03-30 17:54:24 -07001004 * @return filtering objective builder
1005 */
1006 private FilteringObjective.Builder filterObjBuilder(DeviceId deviceId, PortNumber ingressPort,
Charles Chanf909e5b2018-03-02 13:26:22 -08001007 VlanId assignedVlan, IpAddress mcastIp, MacAddress routerMac) {
Charles Chanc91c8782016-03-30 17:54:24 -07001008 FilteringObjective.Builder filtBuilder = DefaultFilteringObjective.builder();
Charles Chan0932eca2016-06-28 16:50:13 -07001009
Julia Fergusonf1d9c342017-08-10 18:15:24 +00001010 if (mcastIp.isIp4()) {
1011 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
1012 .addCondition(Criteria.matchEthDstMasked(MacAddress.IPV4_MULTICAST,
1013 MacAddress.IPV4_MULTICAST_MASK))
1014 .addCondition(Criteria.matchVlanId(egressVlan()))
1015 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1016 } else {
1017 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
1018 .addCondition(Criteria.matchEthDstMasked(MacAddress.IPV6_MULTICAST,
1019 MacAddress.IPV6_MULTICAST_MASK))
1020 .addCondition(Criteria.matchVlanId(egressVlan()))
1021 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1022 }
Charles Chan0932eca2016-06-28 16:50:13 -07001023 TrafficTreatment tt = DefaultTrafficTreatment.builder()
Charles Chanf909e5b2018-03-02 13:26:22 -08001024 .pushVlan().setVlanId(assignedVlan)
1025 .setEthDst(routerMac)
1026 .build();
Charles Chan0932eca2016-06-28 16:50:13 -07001027 filtBuilder.withMeta(tt);
1028
Pier Luigi69f774d2018-02-28 12:10:50 +01001029 return filtBuilder.permit().fromApp(srManager.appId());
Charles Chanc91c8782016-03-30 17:54:24 -07001030 }
1031
1032 /**
1033 * Gets output ports information from treatments.
1034 *
1035 * @param treatments collection of traffic treatments
1036 * @return set of output port numbers
1037 */
1038 private Set<PortNumber> getPorts(Collection<TrafficTreatment> treatments) {
1039 ImmutableSet.Builder<PortNumber> builder = ImmutableSet.builder();
1040 treatments.forEach(treatment -> {
1041 treatment.allInstructions().stream()
1042 .filter(instr -> instr instanceof OutputInstruction)
1043 .forEach(instr -> {
1044 builder.add(((OutputInstruction) instr).port());
1045 });
1046 });
1047 return builder.build();
1048 }
1049
Pier Luigi51ee7c02018-02-23 19:57:40 +01001050 // Utility method to verify is a link is a pair-link
1051 private boolean isPairLink(Link link) {
1052 // Take src id, src port, dst id and dst port
1053 final DeviceId srcId = link.src().deviceId();
1054 final PortNumber srcPort = link.src().port();
1055 final DeviceId dstId = link.dst().deviceId();
1056 final PortNumber dstPort = link.dst().port();
1057 // init as true
1058 boolean isPairLink = true;
1059 try {
1060 // If one of this condition is not true; it is not a pair link
Pier Luigi69f774d2018-02-28 12:10:50 +01001061 if (!(srManager.deviceConfiguration().isEdgeDevice(srcId) &&
1062 srManager.deviceConfiguration().isEdgeDevice(dstId) &&
1063 srManager.deviceConfiguration().getPairDeviceId(srcId).equals(dstId) &&
1064 srManager.deviceConfiguration().getPairLocalPort(srcId).equals(srcPort) &&
1065 srManager.deviceConfiguration().getPairLocalPort(dstId).equals(dstPort))) {
Pier Luigi51ee7c02018-02-23 19:57:40 +01001066 isPairLink = false;
1067 }
1068 } catch (DeviceConfigNotFoundException e) {
1069 // Configuration not provided
1070 log.warn("Could not check if the link {} is pairlink "
1071 + "config not yet provided", link);
1072 isPairLink = false;
1073 }
1074 return isPairLink;
1075 }
1076
Charles Chanc91c8782016-03-30 17:54:24 -07001077 /**
1078 * Gets a path from src to dst.
1079 * If a path was allocated before, returns the allocated path.
1080 * Otherwise, randomly pick one from available paths.
1081 *
1082 * @param src source device ID
1083 * @param dst destination device ID
1084 * @param mcastIp multicast group
1085 * @return an optional path from src to dst
1086 */
1087 private Optional<Path> getPath(DeviceId src, DeviceId dst, IpAddress mcastIp) {
Pier Luigid8a15162018-02-15 16:33:08 +01001088 // Takes a snapshot of the topology
1089 final Topology currentTopology = topologyService.currentTopology();
Charles Chanc91c8782016-03-30 17:54:24 -07001090 List<Path> allPaths = Lists.newArrayList(
Pier Luigid8a15162018-02-15 16:33:08 +01001091 topologyService.getPaths(currentTopology, src, dst)
1092 );
Pier Luigi51ee7c02018-02-23 19:57:40 +01001093 // Create list of valid paths
1094 allPaths.removeIf(path -> path.links().stream().anyMatch(this::isPairLink));
1095 // If there are no valid paths, just exit
Charles Chan72779502016-04-23 17:36:10 -07001096 log.debug("{} path(s) found from {} to {}", allPaths.size(), src, dst);
Charles Chanc91c8782016-03-30 17:54:24 -07001097 if (allPaths.isEmpty()) {
Charles Chanc91c8782016-03-30 17:54:24 -07001098 return Optional.empty();
1099 }
1100
Pier Luigi91573e12018-01-23 16:06:38 +01001101 // Create a map index of suitablity-to-list of paths. For example
1102 // a path in the list associated to the index 1 shares only the
1103 // first hop and it is less suitable of a path belonging to the index
1104 // 2 that shares leaf-spine.
1105 Map<Integer, List<Path>> eligiblePaths = Maps.newHashMap();
1106 // Some init steps
1107 int nhop;
1108 McastStoreKey mcastStoreKey;
1109 Link hop;
1110 PortNumber srcPort;
1111 Set<PortNumber> existingPorts;
1112 NextObjective nextObj;
1113 // Iterate over paths looking for eligible paths
1114 for (Path path : allPaths) {
1115 // Unlikely, it will happen...
1116 if (!src.equals(path.links().get(0).src().deviceId())) {
1117 continue;
1118 }
1119 nhop = 0;
1120 // Iterate over the links
1121 while (nhop < path.links().size()) {
1122 // Get the link and verify if a next related
1123 // to the src device exist in the store
1124 hop = path.links().get(nhop);
1125 mcastStoreKey = new McastStoreKey(mcastIp, hop.src().deviceId());
1126 // It does not exist in the store, exit
1127 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1128 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001129 }
Pier Luigi91573e12018-01-23 16:06:38 +01001130 // Get the output ports on the next
1131 nextObj = mcastNextObjStore.get(mcastStoreKey).value();
1132 existingPorts = getPorts(nextObj.next());
1133 // And the src port on the link
1134 srcPort = hop.src().port();
1135 // the src port is not used as output, exit
1136 if (!existingPorts.contains(srcPort)) {
1137 break;
1138 }
1139 nhop++;
1140 }
1141 // n_hop defines the index
1142 if (nhop > 0) {
1143 eligiblePaths.compute(nhop, (index, paths) -> {
1144 paths = paths == null ? Lists.newArrayList() : paths;
1145 paths.add(path);
1146 return paths;
1147 });
Charles Chanc91c8782016-03-30 17:54:24 -07001148 }
1149 }
Pier Luigi91573e12018-01-23 16:06:38 +01001150
1151 // No suitable paths
1152 if (eligiblePaths.isEmpty()) {
1153 log.debug("No eligiblePath(s) found from {} to {}", src, dst);
1154 // Otherwise, randomly pick a path
1155 Collections.shuffle(allPaths);
1156 return allPaths.stream().findFirst();
1157 }
1158
1159 // Let's take the best ones
1160 Integer bestIndex = eligiblePaths.keySet()
1161 .stream()
1162 .sorted(Comparator.reverseOrder())
1163 .findFirst().orElse(null);
1164 List<Path> bestPaths = eligiblePaths.get(bestIndex);
1165 log.debug("{} eligiblePath(s) found from {} to {}",
1166 bestPaths.size(), src, dst);
1167 // randomly pick a path on the highest index
1168 Collections.shuffle(bestPaths);
1169 return bestPaths.stream().findFirst();
Charles Chanc91c8782016-03-30 17:54:24 -07001170 }
1171
1172 /**
Charles Chan72779502016-04-23 17:36:10 -07001173 * Gets device(s) of given role in given multicast group.
1174 *
1175 * @param mcastIp multicast IP
1176 * @param role multicast role
1177 * @return set of device ID or empty set if not found
1178 */
1179 private Set<DeviceId> getDevice(IpAddress mcastIp, McastRole role) {
1180 return mcastRoleStore.entrySet().stream()
1181 .filter(entry -> entry.getKey().mcastIp().equals(mcastIp) &&
1182 entry.getValue().value() == role)
1183 .map(Map.Entry::getKey).map(McastStoreKey::deviceId)
1184 .collect(Collectors.toSet());
1185 }
1186
1187 /**
Charles Chana8f9dee2016-05-16 18:44:13 -07001188 * Gets source connect point of given multicast group.
1189 *
1190 * @param mcastIp multicast IP
1191 * @return source connect point or null if not found
1192 */
1193 private ConnectPoint getSource(IpAddress mcastIp) {
1194 return srManager.multicastRouteService.getRoutes().stream()
1195 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1196 .map(mcastRoute -> srManager.multicastRouteService.fetchSource(mcastRoute))
1197 .findAny().orElse(null);
1198 }
Pier Luigi92e69be2018-03-02 12:53:37 +01001199 /**
1200 * Gets sinks of given multicast group.
1201 *
1202 * @param mcastIp multicast IP
1203 * @return set of sinks or empty set if not found
1204 */
1205 private Set<ConnectPoint> getSinks(IpAddress mcastIp) {
1206 return srManager.multicastRouteService.getRoutes().stream()
1207 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1208 .map(mcastRoute -> srManager.multicastRouteService.fetchSinks(mcastRoute))
1209 .findAny().orElse(Collections.emptySet());
1210 }
Charles Chana8f9dee2016-05-16 18:44:13 -07001211
1212 /**
Charles Chan72779502016-04-23 17:36:10 -07001213 * Gets groups which is affected by the link down event.
1214 *
1215 * @param link link going down
1216 * @return a set of multicast IpAddress
1217 */
1218 private Set<IpAddress> getAffectedGroups(Link link) {
1219 DeviceId deviceId = link.src().deviceId();
1220 PortNumber port = link.src().port();
1221 return mcastNextObjStore.entrySet().stream()
1222 .filter(entry -> entry.getKey().deviceId().equals(deviceId) &&
1223 getPorts(entry.getValue().value().next()).contains(port))
1224 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1225 .collect(Collectors.toSet());
1226 }
1227
1228 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001229 * Gets groups which are affected by the device down event.
1230 *
1231 * @param deviceId device going down
1232 * @return a set of multicast IpAddress
1233 */
1234 private Set<IpAddress> getAffectedGroups(DeviceId deviceId) {
1235 return mcastNextObjStore.entrySet().stream()
1236 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
1237 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1238 .collect(Collectors.toSet());
1239 }
1240
1241 /**
Charles Chanc91c8782016-03-30 17:54:24 -07001242 * Gets egress VLAN from McastConfig.
1243 *
1244 * @return egress VLAN or VlanId.NONE if not configured
1245 */
1246 private VlanId egressVlan() {
1247 McastConfig mcastConfig =
1248 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1249 return (mcastConfig != null) ? mcastConfig.egressVlan() : VlanId.NONE;
1250 }
1251
1252 /**
1253 * Gets assigned VLAN according to the value of egress VLAN.
Charles Chana8f9dee2016-05-16 18:44:13 -07001254 * If connect point is specified, try to reuse the assigned VLAN on the connect point.
Charles Chanc91c8782016-03-30 17:54:24 -07001255 *
Charles Chana8f9dee2016-05-16 18:44:13 -07001256 * @param cp connect point; Can be null if not specified
1257 * @return assigned VLAN ID
Charles Chanc91c8782016-03-30 17:54:24 -07001258 */
Charles Chana8f9dee2016-05-16 18:44:13 -07001259 private VlanId assignedVlan(ConnectPoint cp) {
1260 // Use the egressVlan if it is tagged
1261 if (!egressVlan().equals(VlanId.NONE)) {
1262 return egressVlan();
1263 }
1264 // Reuse unicast VLAN if the port has subnet configured
1265 if (cp != null) {
Charles Chanf9759582017-10-20 19:09:16 -07001266 VlanId untaggedVlan = srManager.getInternalVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001267 return (untaggedVlan != null) ? untaggedVlan : INTERNAL_VLAN;
Charles Chana8f9dee2016-05-16 18:44:13 -07001268 }
Charles Chan10b0fb72017-02-02 16:20:42 -08001269 // Use DEFAULT_VLAN if none of the above matches
1270 return SegmentRoutingManager.INTERNAL_VLAN;
Charles Chanc91c8782016-03-30 17:54:24 -07001271 }
Charles Chan72779502016-04-23 17:36:10 -07001272
1273 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +01001274 * Gets assigned VLAN according to the value in the meta.
1275 *
1276 * @param nextObjective nextObjective to analyze
1277 * @return assigned VLAN ID
1278 */
1279 private VlanId assignedVlanFromNext(NextObjective nextObjective) {
1280 return ((VlanIdCriterion) nextObjective.meta().getCriterion(VLAN_VID)).vlanId();
1281 }
1282
1283 /**
Charles Chan72779502016-04-23 17:36:10 -07001284 * Gets the spine-facing port on ingress device of given multicast group.
1285 *
1286 * @param mcastIp multicast IP
1287 * @return spine-facing port on ingress device
1288 */
1289 private PortNumber ingressTransitPort(IpAddress mcastIp) {
1290 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
1291 .stream().findAny().orElse(null);
1292 if (ingressDevice != null) {
1293 NextObjective nextObj = mcastNextObjStore
1294 .get(new McastStoreKey(mcastIp, ingressDevice)).value();
1295 Set<PortNumber> ports = getPorts(nextObj.next());
1296
1297 for (PortNumber port : ports) {
1298 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001299 if (srManager.deviceConfiguration() != null &&
1300 srManager.deviceConfiguration().getPortSubnets(ingressDevice, port).isEmpty() &&
Charles Chan82f19972016-05-17 13:13:55 -07001301 !srManager.xConnectHandler.hasXConnect(new ConnectPoint(ingressDevice, port))) {
Charles Chan72779502016-04-23 17:36:10 -07001302 return port;
1303 }
1304 }
1305 }
1306 return null;
1307 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001308
1309 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001310 * Verify if the given device has sinks
1311 * for the multicast group.
1312 *
1313 * @param deviceId device Id
1314 * @param mcastIp multicast IP
1315 * @return true if the device has sink for the group.
1316 * False otherwise.
1317 */
1318 private boolean hasSinks(DeviceId deviceId, IpAddress mcastIp) {
1319 if (deviceId != null) {
1320 // Get the nextobjective
1321 Versioned<NextObjective> versionedNextObj = mcastNextObjStore.get(
1322 new McastStoreKey(mcastIp, deviceId)
1323 );
1324 // If it exists
1325 if (versionedNextObj != null) {
1326 NextObjective nextObj = versionedNextObj.value();
1327 // Retrieves all the output ports
1328 Set<PortNumber> ports = getPorts(nextObj.next());
1329 // Tries to find at least one port that is not spine-facing
1330 for (PortNumber port : ports) {
1331 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001332 if (srManager.deviceConfiguration() != null &&
1333 (!srManager.deviceConfiguration().getPortSubnets(deviceId, port).isEmpty() ||
Pier Luigi580fd8a2018-01-16 10:47:50 +01001334 srManager.xConnectHandler.hasXConnect(new ConnectPoint(deviceId, port)))) {
1335 return true;
1336 }
1337 }
1338 }
1339 }
1340 return false;
1341 }
1342
1343 /**
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001344 * Removes filtering objective for given device and port.
1345 *
1346 * @param deviceId device ID
1347 * @param port ingress port number
1348 * @param assignedVlan assigned VLAN ID
1349 * @param mcastIp multicast IP address
1350 */
1351 private void removeFilterToDevice(DeviceId deviceId, PortNumber port, VlanId assignedVlan, IpAddress mcastIp) {
1352 // Do nothing if the port is configured as suppressed
1353 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
1354 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +01001355 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001356 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
1357 log.info("Ignore suppressed port {}", connectPoint);
1358 return;
1359 }
1360
Charles Chanf909e5b2018-03-02 13:26:22 -08001361 MacAddress routerMac;
1362 try {
1363 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
1364 } catch (DeviceConfigNotFoundException dcnfe) {
1365 log.warn("Fail to push filtering objective since device is not configured. Abort");
1366 return;
1367 }
1368
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001369 FilteringObjective.Builder filtObjBuilder =
Charles Chanf909e5b2018-03-02 13:26:22 -08001370 filterObjBuilder(deviceId, port, assignedVlan, mcastIp, routerMac);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001371 ObjectiveContext context = new DefaultObjectiveContext(
1372 (objective) -> log.debug("Successfully removed filter on {}/{}, vlan {}",
1373 deviceId, port.toLong(), assignedVlan),
1374 (objective, error) ->
1375 log.warn("Failed to remove filter on {}/{}, vlan {}: {}",
1376 deviceId, port.toLong(), assignedVlan, error));
1377 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.remove(context));
1378 }
1379
1380 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +01001381 * Updates filtering objective for given device and port.
1382 * It is called in general when the mcast config has been
1383 * changed.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001384 *
1385 * @param deviceId device ID
1386 * @param portNum ingress port number
1387 * @param vlanId assigned VLAN ID
1388 * @param install true to add, false to remove
1389 */
Pier Luigi69f774d2018-02-28 12:10:50 +01001390 public void updateFilterToDevice(DeviceId deviceId, PortNumber portNum,
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001391 VlanId vlanId, boolean install) {
Pier Luigi35dab3f2018-01-25 16:16:02 +01001392 lastMcastChange = Instant.now();
1393 mcastLock();
1394 try {
1395 // Iterates over the route and updates properly the filtering objective
1396 // on the source device.
1397 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
1398 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
1399 if (source.deviceId().equals(deviceId) && source.port().equals(portNum)) {
1400 if (install) {
1401 addFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group());
1402 } else {
1403 removeFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group());
1404 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001405 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001406 });
1407 } finally {
1408 mcastUnlock();
1409 }
1410 }
1411
Pier Luigi6786b922018-02-02 16:19:11 +01001412 private boolean isLeader(ConnectPoint source) {
1413 // Continue only when we have the mastership on the operation
1414 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1415 // When the source is available we just check the mastership
1416 if (srManager.deviceService.isAvailable(source.deviceId())) {
1417 return false;
1418 }
1419 // Fallback with Leadership service
1420 // source id is used a topic
1421 NodeId leader = srManager.leadershipService.runForLeadership(
1422 source.deviceId().toString()).leaderNodeId();
1423 // Verify if this node is the leader
1424 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1425 return false;
1426 }
1427 }
1428 // Done
1429 return true;
1430 }
1431
Pier Luigi35dab3f2018-01-25 16:16:02 +01001432 /**
1433 * Performs bucket verification operation for all mcast groups in the devices.
1434 * Firstly, it verifies that mcast is stable before trying verification operation.
1435 * Verification consists in creating new nexts with VERIFY operation. Actually,
1436 * the operation is totally delegated to the driver.
1437 */
1438 private final class McastBucketCorrector implements Runnable {
1439
1440 @Override
1441 public void run() {
1442 // Verify if the Mcast has been stable for MCAST_STABLITY_THRESHOLD
1443 if (!isMcastStable()) {
1444 return;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001445 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001446 // Acquires lock
1447 mcastLock();
1448 try {
1449 // Iterates over the routes and verify the related next objectives
1450 srManager.multicastRouteService.getRoutes()
1451 .stream()
1452 .map(McastRoute::group)
1453 .forEach(mcastIp -> {
1454 log.trace("Running mcast buckets corrector for mcast group: {}",
1455 mcastIp);
1456
1457 // For each group we get current information in the store
1458 // and issue a check of the next objectives in place
1459 DeviceId ingressDevice = getDevice(mcastIp, McastRole.INGRESS)
1460 .stream().findAny().orElse(null);
1461 DeviceId transitDevice = getDevice(mcastIp, McastRole.TRANSIT)
1462 .stream().findAny().orElse(null);
1463 Set<DeviceId> egressDevices = getDevice(mcastIp, McastRole.EGRESS);
Pier Luigi92e69be2018-03-02 12:53:37 +01001464 // Get source and sinks from Mcast Route Service and warn about errors
Pier Luigi35dab3f2018-01-25 16:16:02 +01001465 ConnectPoint source = getSource(mcastIp);
Pier Luigi92e69be2018-03-02 12:53:37 +01001466 Set<ConnectPoint> sinks = getSinks(mcastIp);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001467
1468 // Do not proceed if ingress device or source of this group are missing
1469 if (ingressDevice == null || source == null) {
Pier Luigi92e69be2018-03-02 12:53:37 +01001470 if (!sinks.isEmpty()) {
1471 log.warn("Unable to run buckets corrector. " +
1472 "Missing ingress {} or source {} for group {}",
1473 ingressDevice, source, mcastIp);
1474 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001475 return;
1476 }
1477
1478 // Continue only when this instance is the master of source device
1479 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1480 log.trace("Unable to run buckets corrector. " +
1481 "Skip {} due to lack of mastership " +
1482 "of the source device {}",
1483 mcastIp, source.deviceId());
1484 return;
1485 }
1486
1487 // Create the set of the devices to be processed
1488 ImmutableSet.Builder<DeviceId> devicesBuilder = ImmutableSet.builder();
1489 devicesBuilder.add(ingressDevice);
1490 if (transitDevice != null) {
1491 devicesBuilder.add(transitDevice);
1492 }
1493 if (!egressDevices.isEmpty()) {
1494 devicesBuilder.addAll(egressDevices);
1495 }
1496 Set<DeviceId> devicesToProcess = devicesBuilder.build();
1497
1498 // Iterate over the devices
1499 devicesToProcess.forEach(deviceId -> {
1500 McastStoreKey currentKey = new McastStoreKey(mcastIp, deviceId);
1501 // If next exists in our store verify related next objective
1502 if (mcastNextObjStore.containsKey(currentKey)) {
1503 NextObjective currentNext = mcastNextObjStore.get(currentKey).value();
1504 // Get current ports
1505 Set<PortNumber> currentPorts = getPorts(currentNext.next());
1506 // Rebuild the next objective
1507 currentNext = nextObjBuilder(
1508 mcastIp,
1509 assignedVlan(deviceId.equals(source.deviceId()) ? source : null),
1510 currentPorts,
1511 currentNext.id()
1512 ).verify();
1513 // Send to the flowobjective service
1514 srManager.flowObjectiveService.next(deviceId, currentNext);
1515 } else {
Pier Luigid8a15162018-02-15 16:33:08 +01001516 log.warn("Unable to run buckets corrector. " +
Pier Luigi35dab3f2018-01-25 16:16:02 +01001517 "Missing next for {} and group {}",
1518 deviceId, mcastIp);
1519 }
1520 });
1521
1522 });
1523 } finally {
1524 // Finally, it releases the lock
1525 mcastUnlock();
1526 }
1527
1528 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001529 }
Pier Luigi0f9635b2018-01-15 18:06:43 +01001530
1531 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
1532 // If mcast ip is present
1533 if (mcastIp != null) {
1534 return mcastNextObjStore.entrySet().stream()
1535 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1536 .collect(Collectors.toMap(Map.Entry::getKey,
1537 entry -> entry.getValue().value().id()));
1538 }
1539 // Otherwise take all the groups
1540 return mcastNextObjStore.entrySet().stream()
1541 .collect(Collectors.toMap(Map.Entry::getKey,
1542 entry -> entry.getValue().value().id()));
1543 }
1544
Pier Luigi69f774d2018-02-28 12:10:50 +01001545 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +01001546 // If mcast ip is present
1547 if (mcastIp != null) {
1548 return mcastRoleStore.entrySet().stream()
1549 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1550 .collect(Collectors.toMap(Map.Entry::getKey,
1551 entry -> entry.getValue().value()));
1552 }
1553 // Otherwise take all the groups
1554 return mcastRoleStore.entrySet().stream()
1555 .collect(Collectors.toMap(Map.Entry::getKey,
1556 entry -> entry.getValue().value()));
1557 }
1558
1559 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
1560 Map<ConnectPoint, List<ConnectPoint>> mcastPaths = Maps.newHashMap();
1561 // Get the source
1562 ConnectPoint source = getSource(mcastIp);
1563 // Source cannot be null, we don't know the starting point
1564 if (source != null) {
1565 // Init steps
1566 Set<DeviceId> visited = Sets.newHashSet();
1567 List<ConnectPoint> currentPath = Lists.newArrayList(
1568 source
1569 );
1570 // Build recursively the mcast paths
1571 buildMcastPaths(source.deviceId(), visited, mcastPaths, currentPath, mcastIp);
1572 }
1573 return mcastPaths;
1574 }
1575
1576 private void buildMcastPaths(DeviceId toVisit, Set<DeviceId> visited,
1577 Map<ConnectPoint, List<ConnectPoint>> mcastPaths,
1578 List<ConnectPoint> currentPath, IpAddress mcastIp) {
1579 // If we have visited the node to visit
1580 // there is a loop
1581 if (visited.contains(toVisit)) {
1582 return;
1583 }
1584 // Visit next-hop
1585 visited.add(toVisit);
1586 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, toVisit);
1587 // Looking for next-hops
1588 if (mcastNextObjStore.containsKey(mcastStoreKey)) {
1589 // Build egress connectpoints
1590 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
1591 // Get Ports
1592 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
1593 // Build relative cps
1594 ImmutableSet.Builder<ConnectPoint> cpBuilder = ImmutableSet.builder();
1595 outputPorts.forEach(portNumber -> cpBuilder.add(new ConnectPoint(toVisit, portNumber)));
1596 Set<ConnectPoint> egressPoints = cpBuilder.build();
1597 // Define other variables for the next steps
1598 Set<Link> egressLinks;
1599 List<ConnectPoint> newCurrentPath;
1600 Set<DeviceId> newVisited;
1601 DeviceId newToVisit;
1602 for (ConnectPoint egressPoint : egressPoints) {
1603 egressLinks = srManager.linkService.getEgressLinks(egressPoint);
1604 // If it does not have egress links, stop
1605 if (egressLinks.isEmpty()) {
1606 // Add the connect points to the path
1607 newCurrentPath = Lists.newArrayList(currentPath);
1608 newCurrentPath.add(0, egressPoint);
1609 // Save in the map
1610 mcastPaths.put(egressPoint, newCurrentPath);
1611 } else {
1612 newVisited = Sets.newHashSet(visited);
1613 // Iterate over the egress links for the next hops
1614 for (Link egressLink : egressLinks) {
1615 // Update to visit
1616 newToVisit = egressLink.dst().deviceId();
1617 // Add the connect points to the path
1618 newCurrentPath = Lists.newArrayList(currentPath);
1619 newCurrentPath.add(0, egressPoint);
1620 newCurrentPath.add(0, egressLink.dst());
1621 // Go to the next hop
1622 buildMcastPaths(newToVisit, newVisited, mcastPaths, newCurrentPath, mcastIp);
1623 }
1624 }
1625 }
1626 }
1627 }
1628
Charles Chanc91c8782016-03-30 17:54:24 -07001629}