blob: a791ecbc12b5e0e7a112bed6db75272c1d84b9ce [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
Pier Luigi35dab3f2018-01-25 16:16:02 +010089import static java.util.concurrent.Executors.newScheduledThreadPool;
90import static org.onlab.util.Tools.groupedThreads;
Pier Luigid29ca7c2018-02-28 17:24:03 +010091import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
92import static org.onosproject.net.mcast.McastEvent.Type.ROUTE_REMOVED;
93import static org.onosproject.net.mcast.McastEvent.Type.SOURCE_ADDED;
94import static org.onosproject.net.mcast.McastEvent.Type.SOURCE_UPDATED;
Charles Chan10b0fb72017-02-02 16:20:42 -080095import static org.onosproject.segmentrouting.SegmentRoutingManager.INTERNAL_VLAN;
Pier979e61a2018-03-07 11:42:50 +010096import static org.onosproject.segmentrouting.mcast.McastRole.EGRESS;
97import static org.onosproject.segmentrouting.mcast.McastRole.INGRESS;
98import static org.onosproject.segmentrouting.mcast.McastRole.TRANSIT;
Charles Chanc91c8782016-03-30 17:54:24 -070099
100/**
Pier Luigi69f774d2018-02-28 12:10:50 +0100101 * Handles Multicast related events.
Charles Chanc91c8782016-03-30 17:54:24 -0700102 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700103public class McastHandler {
104 private static final Logger log = LoggerFactory.getLogger(McastHandler.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700105 private final SegmentRoutingManager srManager;
106 private final ApplicationId coreAppId;
Charles Chan82f19972016-05-17 13:13:55 -0700107 private final StorageService storageService;
108 private final TopologyService topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700109 private final ConsistentMap<McastStoreKey, NextObjective> mcastNextObjStore;
110 private final KryoNamespace.Builder mcastKryo;
111 private final ConsistentMap<McastStoreKey, McastRole> mcastRoleStore;
112
Pier Luigid29ca7c2018-02-28 17:24:03 +0100113 // Wait time for the cache
114 private static final int WAIT_TIME_MS = 1000;
115 /**
116 * The mcastEventCache is implemented to avoid race condition by giving more time to the
117 * underlying subsystems to process previous calls.
118 */
119 private Cache<McastCacheKey, McastEvent> mcastEventCache = CacheBuilder.newBuilder()
120 .expireAfterWrite(WAIT_TIME_MS, TimeUnit.MILLISECONDS)
121 .removalListener((RemovalNotification<McastCacheKey, McastEvent> notification) -> {
122 // Get group ip, sink and related event
123 IpAddress mcastIp = notification.getKey().mcastIp();
124 ConnectPoint sink = notification.getKey().sink();
125 McastEvent mcastEvent = notification.getValue();
126 RemovalCause cause = notification.getCause();
127 log.debug("mcastEventCache removal event. group={}, sink={}, mcastEvent={}, cause={}",
128 mcastIp, sink, mcastEvent, cause);
129 // If it expires or it has been replaced, we deque the event
130 switch (notification.getCause()) {
131 case REPLACED:
132 case EXPIRED:
133 dequeueMcastEvent(mcastEvent);
134 break;
135 default:
136 break;
137 }
138 }).build();
139
140 private void enqueueMcastEvent(McastEvent mcastEvent) {
141 log.debug("Enqueue mcastEvent {}", mcastEvent);
142 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
143 // Let's create the keys of the cache
144 ImmutableSet.Builder<ConnectPoint> sinksBuilder = ImmutableSet.builder();
145 // For this event we will have a set of sinks
146 if (mcastEvent.type() == SOURCE_ADDED ||
147 mcastEvent.type() == SOURCE_UPDATED ||
148 mcastEvent.type() == ROUTE_REMOVED) {
149 // Add all the sinks
150 sinksBuilder.addAll(mcastRouteInfo.sinks());
151 } else {
152 // We have just one sink in this case
153 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
154 // It is always true, unless something of bad happened
155 // in the mcast route store
156 if (sink != null) {
157 sinksBuilder.add(sink);
158 }
159 }
160 // Push the elements in the cache
161 sinksBuilder.build().forEach(sink -> {
162 McastCacheKey cacheKey = new McastCacheKey(mcastRouteInfo.route().group(),
163 sink);
164 mcastEventCache.put(cacheKey, mcastEvent);
165 });
166 }
167
168 private void dequeueMcastEvent(McastEvent mcastEvent) {
169 log.debug("Dequeue mcastEvent {}", mcastEvent);
170 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
171 // Get source, mcast group
172 ConnectPoint source = mcastRouteInfo.source().orElse(null);
173 IpAddress mcastIp = mcastRouteInfo.route().group();
174 // According to the event type let's call the proper method
175 switch (mcastEvent.type()) {
176 case SOURCE_ADDED:
177 // Get all the sinks and process
178 Set<ConnectPoint> sinks = mcastRouteInfo.sinks();
179 sinks.forEach(sink -> processSinkAddedInternal(source, sink, mcastIp));
180 break;
181 case SOURCE_UPDATED:
182 // Get old source
183 ConnectPoint oldSource = mcastEvent.prevSubject().source().orElse(null);
184 // Just the first cached element will be processed
185 processSourceUpdatedInternal(mcastIp, source, oldSource);
186 break;
187 case ROUTE_REMOVED:
188 // Process the route removed, just the first cached element will be processed
189 processRouteRemovedInternal(source, mcastIp);
190 break;
191 case SINK_ADDED:
192 // Get the only sink and process
193 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
194 processSinkAddedInternal(source, sink, mcastIp);
195 break;
196 case SINK_REMOVED:
197 sink = mcastRouteInfo.sink().orElse(null);
198 processSinkRemovedInternal(source, sink, mcastIp);
199 break;
200 default:
201 break;
202 }
203 }
204
Pier Luigi35dab3f2018-01-25 16:16:02 +0100205 // Mcast lock to serialize local operations
206 private final Lock mcastLock = new ReentrantLock();
207
208 /**
209 * Acquires the lock used when making mcast changes.
210 */
211 private void mcastLock() {
212 mcastLock.lock();
213 }
214
215 /**
216 * Releases the lock used when making mcast changes.
217 */
218 private void mcastUnlock() {
219 mcastLock.unlock();
220 }
221
222 // Stability threshold for Mcast. Seconds
223 private static final long MCAST_STABLITY_THRESHOLD = 5;
224 // Last change done
225 private Instant lastMcastChange = Instant.now();
226
227 /**
228 * Determines if mcast in the network has been stable in the last
229 * MCAST_STABLITY_THRESHOLD seconds, by comparing the current time
230 * to the last mcast change timestamp.
231 *
232 * @return true if stable
233 */
234 private boolean isMcastStable() {
235 long last = (long) (lastMcastChange.toEpochMilli() / 1000.0);
236 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das97241862018-02-14 14:14:54 -0800237 log.trace("Mcast stable since {}s", now - last);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100238 return (now - last) > MCAST_STABLITY_THRESHOLD;
239 }
240
241 // Verify interval for Mcast
242 private static final long MCAST_VERIFY_INTERVAL = 30;
243
244 // Executor for mcast bucket corrector
245 private ScheduledExecutorService executorService
Pier Luigid29ca7c2018-02-28 17:24:03 +0100246 = newScheduledThreadPool(1, groupedThreads("mcastWorker", "mcastWorker-%d", log));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100247
Charles Chan72779502016-04-23 17:36:10 -0700248 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700249 * Constructs the McastEventHandler.
250 *
251 * @param srManager Segment Routing manager
252 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700253 public McastHandler(SegmentRoutingManager srManager) {
Charles Chanc91c8782016-03-30 17:54:24 -0700254 coreAppId = srManager.coreService.getAppId(CoreService.CORE_APP_NAME);
Charles Chanc91c8782016-03-30 17:54:24 -0700255 this.srManager = srManager;
256 this.storageService = srManager.storageService;
257 this.topologyService = srManager.topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700258 mcastKryo = new KryoNamespace.Builder()
Charles Chanc91c8782016-03-30 17:54:24 -0700259 .register(KryoNamespaces.API)
Charles Chan72779502016-04-23 17:36:10 -0700260 .register(McastStoreKey.class)
261 .register(McastRole.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700262 mcastNextObjStore = storageService
Charles Chan72779502016-04-23 17:36:10 -0700263 .<McastStoreKey, NextObjective>consistentMapBuilder()
Charles Chanc91c8782016-03-30 17:54:24 -0700264 .withName("onos-mcast-nextobj-store")
Charles Chan4922a172016-05-23 16:45:45 -0700265 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-NextObj")))
Charles Chanc91c8782016-03-30 17:54:24 -0700266 .build();
Charles Chan72779502016-04-23 17:36:10 -0700267 mcastRoleStore = storageService
268 .<McastStoreKey, McastRole>consistentMapBuilder()
269 .withName("onos-mcast-role-store")
Charles Chan4922a172016-05-23 16:45:45 -0700270 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-Role")))
Charles Chan72779502016-04-23 17:36:10 -0700271 .build();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100272 // Init the executor service and the buckets corrector
273 executorService.scheduleWithFixedDelay(new McastBucketCorrector(), 10,
274 MCAST_VERIFY_INTERVAL,
275 TimeUnit.SECONDS);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100276 // Schedule the clean up, this will allow the processing of the expired events
277 executorService.scheduleAtFixedRate(mcastEventCache::cleanUp, 0,
278 WAIT_TIME_MS, TimeUnit.MILLISECONDS);
Charles Chan72779502016-04-23 17:36:10 -0700279 }
280
281 /**
282 * Read initial multicast from mcast store.
283 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100284 public void init() {
Charles Chan72779502016-04-23 17:36:10 -0700285 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
286 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
287 Set<ConnectPoint> sinks = srManager.multicastRouteService.fetchSinks(mcastRoute);
288 sinks.forEach(sink -> {
289 processSinkAddedInternal(source, sink, mcastRoute.group());
290 });
291 });
Charles Chanc91c8782016-03-30 17:54:24 -0700292 }
293
294 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100295 * Clean up when deactivating the application.
296 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100297 public void terminate() {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100298 executorService.shutdown();
299 }
300
301 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +0100302 * Processes the SOURCE_ADDED, SOURCE_UPDATED, SINK_ADDED,
303 * SINK_REMOVED and ROUTE_REMOVED events.
Charles Chanc91c8782016-03-30 17:54:24 -0700304 *
305 * @param event McastEvent with SOURCE_ADDED type
306 */
Pier Luigid29ca7c2018-02-28 17:24:03 +0100307 public void processMcastEvent(McastEvent event) {
308 log.info("process {}", event);
309 // Verify if it is a complete event
Charles Chanc91c8782016-03-30 17:54:24 -0700310 McastRouteInfo mcastRouteInfo = event.subject();
311 if (!mcastRouteInfo.isComplete()) {
Pier Luigid29ca7c2018-02-28 17:24:03 +0100312 log.info("Incompleted McastRouteInfo. Abort {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -0700313 return;
314 }
Pier Luigid29ca7c2018-02-28 17:24:03 +0100315 // Just enqueue for now
316 enqueueMcastEvent(event);
Pier Luigi6786b922018-02-02 16:19:11 +0100317 }
318
319 /**
Pier Luigie80d6b42018-02-26 12:31:38 +0100320 * Process the SOURCE_UPDATED event.
321 *
322 * @param newSource the updated srouce info
323 * @param oldSource the outdated source info
324 */
325 private void processSourceUpdatedInternal(IpAddress mcastIp,
326 ConnectPoint newSource,
327 ConnectPoint oldSource) {
328 lastMcastChange = Instant.now();
329 mcastLock();
330 try {
331 log.debug("Processing source updated for group {}", mcastIp);
332
333 // Build key for the store and retrieve old data
334 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, oldSource.deviceId());
335
336 // Verify leadership on the operation
337 if (!isLeader(oldSource)) {
338 log.debug("Skip {} due to lack of leadership", mcastIp);
339 return;
340 }
341
342 // This device is not serving this multicast group
343 if (!mcastRoleStore.containsKey(mcastStoreKey) ||
344 !mcastNextObjStore.containsKey(mcastStoreKey)) {
345 log.warn("{} is not serving {}. Abort.", oldSource.deviceId(), mcastIp);
346 return;
347 }
348 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
349 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
350
Pier Luigid29ca7c2018-02-28 17:24:03 +0100351 // This an optimization to avoid unnecessary removal and add
352 if (!assignedVlanFromNext(nextObjective).equals(assignedVlan(newSource))) {
353 // Let's remove old flows and groups
354 removeGroupFromDevice(oldSource.deviceId(), mcastIp, assignedVlan(oldSource));
355 // Push new flows and group
356 outputPorts.forEach(portNumber -> addPortToDevice(newSource.deviceId(), portNumber,
357 mcastIp, assignedVlan(newSource)));
358 }
Pier Luigie80d6b42018-02-26 12:31:38 +0100359 addFilterToDevice(newSource.deviceId(), newSource.port(),
Pier979e61a2018-03-07 11:42:50 +0100360 assignedVlan(newSource), mcastIp, INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100361 // Setup mcast roles
362 mcastRoleStore.put(new McastStoreKey(mcastIp, newSource.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100363 INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100364 } finally {
365 mcastUnlock();
366 }
367 }
368
369 /**
Pier Luigi6786b922018-02-02 16:19:11 +0100370 * Removes the entire mcast tree related to this group.
371 *
372 * @param mcastIp multicast group IP address
373 */
374 private void processRouteRemovedInternal(ConnectPoint source, IpAddress mcastIp) {
375 lastMcastChange = Instant.now();
376 mcastLock();
377 try {
Pier Luigie80d6b42018-02-26 12:31:38 +0100378 log.debug("Processing route removed for group {}", mcastIp);
Pier Luigi6786b922018-02-02 16:19:11 +0100379
380 // Find out the ingress, transit and egress device of the affected group
Pier979e61a2018-03-07 11:42:50 +0100381 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi6786b922018-02-02 16:19:11 +0100382 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700383 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100384 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi6786b922018-02-02 16:19:11 +0100385
386 // Verify leadership on the operation
387 if (!isLeader(source)) {
388 log.debug("Skip {} due to lack of leadership", mcastIp);
389 return;
390 }
391
Pier1a7e0c02018-03-12 15:00:54 -0700392 // If there are no egress devices, sinks could be only on the ingress
Pier Luigi6786b922018-02-02 16:19:11 +0100393 if (!egressDevices.isEmpty()) {
394 egressDevices.forEach(
395 deviceId -> removeGroupFromDevice(deviceId, mcastIp, assignedVlan(null))
396 );
397 }
Pier1a7e0c02018-03-12 15:00:54 -0700398 // Transit could be empty if sinks are on the ingress
399 if (!transitDevices.isEmpty()) {
400 transitDevices.forEach(
401 deviceId -> removeGroupFromDevice(deviceId, mcastIp, assignedVlan(null))
402 );
Pier Luigi6786b922018-02-02 16:19:11 +0100403 }
404 // Ingress device should be not null
405 if (ingressDevice != null) {
406 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
407 }
Pier Luigi6786b922018-02-02 16:19:11 +0100408 } finally {
409 mcastUnlock();
410 }
411 }
412
413 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100414 * Removes a path from source to sink for given multicast group.
415 *
416 * @param source connect point of the multicast source
417 * @param sink connection point of the multicast sink
418 * @param mcastIp multicast group IP address
419 */
420 private void processSinkRemovedInternal(ConnectPoint source, ConnectPoint sink,
421 IpAddress mcastIp) {
422 lastMcastChange = Instant.now();
423 mcastLock();
424 try {
Pier Luigi6786b922018-02-02 16:19:11 +0100425 // Verify leadership on the operation
426 if (!isLeader(source)) {
427 log.debug("Skip {} due to lack of leadership", mcastIp);
Charles Chanc91c8782016-03-30 17:54:24 -0700428 return;
429 }
Charles Chanc91c8782016-03-30 17:54:24 -0700430
Pier Luigi92e69be2018-03-02 12:53:37 +0100431 boolean isLast = false;
Pier Luigi35dab3f2018-01-25 16:16:02 +0100432 // When source and sink are on the same device
433 if (source.deviceId().equals(sink.deviceId())) {
434 // Source and sink are on even the same port. There must be something wrong.
435 if (source.port().equals(sink.port())) {
436 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
437 mcastIp, sink, source);
438 return;
439 }
Pier Luigi92e69be2018-03-02 12:53:37 +0100440 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
441 if (isLast) {
442 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
443 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100444 return;
445 }
Charles Chanc91c8782016-03-30 17:54:24 -0700446
Pier Luigi35dab3f2018-01-25 16:16:02 +0100447 // Process the egress device
Pier Luigi92e69be2018-03-02 12:53:37 +0100448 isLast = removePortFromDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100449 if (isLast) {
450 mcastRoleStore.remove(new McastStoreKey(mcastIp, sink.deviceId()));
451 }
452
453 // If this is the last sink on the device, also update upstream
454 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
455 if (mcastPath.isPresent()) {
456 List<Link> links = Lists.newArrayList(mcastPath.get().links());
457 Collections.reverse(links);
458 for (Link link : links) {
459 if (isLast) {
460 isLast = removePortFromDevice(
461 link.src().deviceId(),
462 link.src().port(),
463 mcastIp,
464 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null)
465 );
Pier Luigi92e69be2018-03-02 12:53:37 +0100466 if (isLast) {
467 mcastRoleStore.remove(new McastStoreKey(mcastIp, link.src().deviceId()));
468 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100469 }
Charles Chanc91c8782016-03-30 17:54:24 -0700470 }
471 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100472 } finally {
473 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700474 }
475 }
476
477 /**
478 * Establishes a path from source to sink for given multicast group.
479 *
480 * @param source connect point of the multicast source
481 * @param sink connection point of the multicast sink
482 * @param mcastIp multicast group IP address
483 */
484 private void processSinkAddedInternal(ConnectPoint source, ConnectPoint sink,
485 IpAddress mcastIp) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100486 lastMcastChange = Instant.now();
487 mcastLock();
488 try {
489 // Continue only when this instance is the master of source device
490 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
491 log.debug("Skip {} due to lack of mastership of the source device {}",
492 mcastIp, source.deviceId());
Charles Chanc91c8782016-03-30 17:54:24 -0700493 return;
494 }
Charles Chanc91c8782016-03-30 17:54:24 -0700495
Pier Luigi35dab3f2018-01-25 16:16:02 +0100496 // Process the ingress device
Pier979e61a2018-03-07 11:42:50 +0100497 addFilterToDevice(source.deviceId(), source.port(),
498 assignedVlan(source), mcastIp, INGRESS);
Charles Chan72779502016-04-23 17:36:10 -0700499
Pier Luigi35dab3f2018-01-25 16:16:02 +0100500 // When source and sink are on the same device
501 if (source.deviceId().equals(sink.deviceId())) {
502 // Source and sink are on even the same port. There must be something wrong.
503 if (source.port().equals(sink.port())) {
504 log.warn("Skip {} since sink {} is on the same port of source {}. Abort",
505 mcastIp, sink, source);
506 return;
507 }
508 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(source));
Pier979e61a2018-03-07 11:42:50 +0100509 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()), INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100510 return;
511 }
Charles Chan72779502016-04-23 17:36:10 -0700512
Pier Luigi35dab3f2018-01-25 16:16:02 +0100513 // Find a path. If present, create/update groups and flows for each hop
514 Optional<Path> mcastPath = getPath(source.deviceId(), sink.deviceId(), mcastIp);
515 if (mcastPath.isPresent()) {
516 List<Link> links = mcastPath.get().links();
Charles Chan72779502016-04-23 17:36:10 -0700517
Pier1a7e0c02018-03-12 15:00:54 -0700518 // Setup mcast role for ingress
519 mcastRoleStore.put(new McastStoreKey(mcastIp, source.deviceId()),
520 INGRESS);
521
522 // Setup properly the transit
Pier Luigi35dab3f2018-01-25 16:16:02 +0100523 links.forEach(link -> {
524 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
525 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
Pier979e61a2018-03-07 11:42:50 +0100526 addFilterToDevice(link.dst().deviceId(), link.dst().port(),
527 assignedVlan(null), mcastIp, null);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100528 });
529
Pier1a7e0c02018-03-12 15:00:54 -0700530 // Setup mcast role for the transit
531 links.stream()
532 .filter(link -> !link.dst().deviceId().equals(sink.deviceId()))
533 .forEach(link -> mcastRoleStore.put(new McastStoreKey(mcastIp, link.dst().deviceId()),
534 TRANSIT));
535
Pier Luigi35dab3f2018-01-25 16:16:02 +0100536 // Process the egress device
537 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
Pier1a7e0c02018-03-12 15:00:54 -0700538 // Setup mcast role for egress
Pier Luigi35dab3f2018-01-25 16:16:02 +0100539 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100540 EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100541 } else {
542 log.warn("Unable to find a path from {} to {}. Abort sinkAdded",
543 source.deviceId(), sink.deviceId());
544 }
545 } finally {
546 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700547 }
548 }
549
550 /**
Charles Chan72779502016-04-23 17:36:10 -0700551 * Processes the LINK_DOWN event.
552 *
553 * @param affectedLink Link that is going down
554 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100555 public void processLinkDown(Link affectedLink) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100556 lastMcastChange = Instant.now();
557 mcastLock();
558 try {
559 // Get groups affected by the link down event
560 getAffectedGroups(affectedLink).forEach(mcastIp -> {
561 // TODO Optimize when the group editing is in place
562 log.debug("Processing link down {} for group {}",
563 affectedLink, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100564
Pier Luigi35dab3f2018-01-25 16:16:02 +0100565 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100566 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100567 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700568 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100569 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100570 ConnectPoint source = getSource(mcastIp);
Charles Chana8f9dee2016-05-16 18:44:13 -0700571
Pier1a7e0c02018-03-12 15:00:54 -0700572 // Do not proceed if ingress device or source of this group are missing
573 // If sinks are in other leafs, we have ingress, transit, egress, and source
574 // If sinks are in the same leaf, we have just ingress and source
575 if (ingressDevice == null || source == null) {
576 log.warn("Missing ingress {} or source {} for group {}",
577 ingressDevice, source, mcastIp);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100578 return;
Charles Chan72779502016-04-23 17:36:10 -0700579 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100580
581 // Continue only when this instance is the master of source device
582 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
583 log.debug("Skip {} due to lack of mastership of the source device {}",
584 source.deviceId());
585 return;
586 }
587
588 // Remove entire transit
Pier1a7e0c02018-03-12 15:00:54 -0700589 transitDevices.forEach(transitDevice ->
590 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null)));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100591
Pier1a7e0c02018-03-12 15:00:54 -0700592 // Remove transit-facing ports on the ingress device
593 removeIngressTransitPorts(mcastIp, ingressDevice, source);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100594
595 // Construct a new path for each egress device
596 egressDevices.forEach(egressDevice -> {
597 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
598 if (mcastPath.isPresent()) {
599 installPath(mcastIp, source, mcastPath.get());
600 } else {
601 log.warn("Fail to recover egress device {} from link failure {}",
602 egressDevice, affectedLink);
603 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
604 }
605 });
Charles Chan72779502016-04-23 17:36:10 -0700606 });
Pier Luigi35dab3f2018-01-25 16:16:02 +0100607 } finally {
608 mcastUnlock();
609 }
Charles Chan72779502016-04-23 17:36:10 -0700610 }
611
612 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +0100613 * Process the DEVICE_DOWN event.
614 *
615 * @param deviceDown device going down
616 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100617 public void processDeviceDown(DeviceId deviceDown) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100618 lastMcastChange = Instant.now();
619 mcastLock();
620 try {
621 // Get the mcast groups affected by the device going down
622 getAffectedGroups(deviceDown).forEach(mcastIp -> {
623 // TODO Optimize when the group editing is in place
624 log.debug("Processing device down {} for group {}",
625 deviceDown, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100626
Pier Luigi35dab3f2018-01-25 16:16:02 +0100627 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100628 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100629 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -0700630 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +0100631 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100632 ConnectPoint source = getSource(mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100633
Pier Luigi35dab3f2018-01-25 16:16:02 +0100634 // Do not proceed if ingress device or source of this group are missing
635 // If sinks are in other leafs, we have ingress, transit, egress, and source
636 // If sinks are in the same leaf, we have just ingress and source
637 if (ingressDevice == null || source == null) {
638 log.warn("Missing ingress {} or source {} for group {}",
639 ingressDevice, source, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100640 return;
641 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100642
Pier Luigi6786b922018-02-02 16:19:11 +0100643 // Verify leadership on the operation
644 if (!isLeader(source)) {
645 log.debug("Skip {} due to lack of leadership", mcastIp);
646 return;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100647 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100648
649 // If it exists, we have to remove it in any case
Pier1a7e0c02018-03-12 15:00:54 -0700650 if (!transitDevices.isEmpty()) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100651 // Remove entire transit
Pier1a7e0c02018-03-12 15:00:54 -0700652 transitDevices.forEach(transitDevice ->
653 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null)));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100654 }
655 // If the ingress is down
656 if (ingressDevice.equals(deviceDown)) {
657 // Remove entire ingress
658 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
659 // If other sinks different from the ingress exist
660 if (!egressDevices.isEmpty()) {
661 // Remove all the remaining egress
662 egressDevices.forEach(
663 egressDevice -> removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null))
664 );
Pier Luigi580fd8a2018-01-16 10:47:50 +0100665 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100666 } else {
667 // Egress or transit could be down at this point
Pier1a7e0c02018-03-12 15:00:54 -0700668 // Get the ingress-transit ports if they exist
669 removeIngressTransitPorts(mcastIp, ingressDevice, source);
670
Pier Luigi35dab3f2018-01-25 16:16:02 +0100671 // One of the egress device is down
672 if (egressDevices.contains(deviceDown)) {
673 // Remove entire device down
674 removeGroupFromDevice(deviceDown, mcastIp, assignedVlan(null));
675 // Remove the device down from egress
676 egressDevices.remove(deviceDown);
677 // If there are no more egress and ingress does not have sinks
678 if (egressDevices.isEmpty() && !hasSinks(ingressDevice, mcastIp)) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100679 // We have done
680 return;
681 }
682 }
683 // Construct a new path for each egress device
684 egressDevices.forEach(egressDevice -> {
685 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
686 // If there is a new path
687 if (mcastPath.isPresent()) {
688 // Let's install the new mcast path for this egress
689 installPath(mcastIp, source, mcastPath.get());
690 } else {
691 // We were not able to find an alternative path for this egress
692 log.warn("Fail to recover egress device {} from device down {}",
693 egressDevice, deviceDown);
694 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
695 }
696 });
697 }
698 });
699 } finally {
700 mcastUnlock();
701 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100702 }
703
704 /**
Pier1a7e0c02018-03-12 15:00:54 -0700705 * Utility method to remove all the ingress transit ports.
706 *
707 * @param mcastIp the group ip
708 * @param ingressDevice the ingress device for this group
709 * @param source the source connect point
710 */
711 private void removeIngressTransitPorts(IpAddress mcastIp, DeviceId ingressDevice,
712 ConnectPoint source) {
713 Set<PortNumber> ingressTransitPorts = ingressTransitPort(mcastIp);
714 ingressTransitPorts.forEach(ingressTransitPort -> {
715 if (ingressTransitPort != null) {
716 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
717 mcastIp, assignedVlan(source));
718 if (isLast) {
719 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
720 }
721 }
722 });
723 }
724
725 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700726 * Adds filtering objective for given device and port.
727 *
728 * @param deviceId device ID
729 * @param port ingress port number
730 * @param assignedVlan assigned VLAN ID
731 */
Pier979e61a2018-03-07 11:42:50 +0100732 private void addFilterToDevice(DeviceId deviceId, PortNumber port,
733 VlanId assignedVlan, IpAddress mcastIp, McastRole mcastRole) {
Charles Chanc91c8782016-03-30 17:54:24 -0700734 // Do nothing if the port is configured as suppressed
Charles Chan370a65b2016-05-10 17:29:47 -0700735 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
736 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +0100737 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Charles Chan370a65b2016-05-10 17:29:47 -0700738 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
739 log.info("Ignore suppressed port {}", connectPoint);
Charles Chanc91c8782016-03-30 17:54:24 -0700740 return;
741 }
742
Charles Chanf909e5b2018-03-02 13:26:22 -0800743 MacAddress routerMac;
744 try {
745 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
746 } catch (DeviceConfigNotFoundException dcnfe) {
747 log.warn("Fail to push filtering objective since device is not configured. Abort");
748 return;
749 }
750
Charles Chanc91c8782016-03-30 17:54:24 -0700751 FilteringObjective.Builder filtObjBuilder =
Pier979e61a2018-03-07 11:42:50 +0100752 filterObjBuilder(port, assignedVlan, mcastIp, routerMac, mcastRole);
Charles Chan72779502016-04-23 17:36:10 -0700753 ObjectiveContext context = new DefaultObjectiveContext(
754 (objective) -> log.debug("Successfully add filter on {}/{}, vlan {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800755 deviceId, port.toLong(), assignedVlan),
Charles Chan72779502016-04-23 17:36:10 -0700756 (objective, error) ->
757 log.warn("Failed to add filter on {}/{}, vlan {}: {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800758 deviceId, port.toLong(), assignedVlan, error));
Charles Chan72779502016-04-23 17:36:10 -0700759 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.add(context));
Charles Chanc91c8782016-03-30 17:54:24 -0700760 }
761
762 /**
763 * Adds a port to given multicast group on given device. This involves the
764 * update of L3 multicast group and multicast routing table entry.
765 *
766 * @param deviceId device ID
767 * @param port port to be added
768 * @param mcastIp multicast group
769 * @param assignedVlan assigned VLAN ID
770 */
771 private void addPortToDevice(DeviceId deviceId, PortNumber port,
772 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700773 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700774 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Pier Luigi4f0dd212018-01-19 10:24:53 +0100775 NextObjective newNextObj;
Charles Chan72779502016-04-23 17:36:10 -0700776 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700777 // First time someone request this mcast group via this device
778 portBuilder.add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100779 // New nextObj
780 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
781 portBuilder.build(), null).add();
782 // Store the new port
783 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700784 } else {
785 // This device already serves some subscribers of this mcast group
Charles Chan72779502016-04-23 17:36:10 -0700786 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700787 // Stop if the port is already in the nextobj
788 Set<PortNumber> existingPorts = getPorts(nextObj.next());
789 if (existingPorts.contains(port)) {
790 log.info("NextObj for {}/{} already exists. Abort", deviceId, port);
791 return;
792 }
Pier Luigi4f0dd212018-01-19 10:24:53 +0100793 // Let's add the port and reuse the previous one
Yuta HIGUCHIbef07b52018-02-09 18:05:23 -0800794 portBuilder.addAll(existingPorts).add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100795 // Reuse previous nextObj
796 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
797 portBuilder.build(), nextObj.id()).addToExisting();
798 // Store the final next objective and send only the difference to the driver
799 mcastNextObjStore.put(mcastStoreKey, newNextObj);
800 // Add just the new port
801 portBuilder = ImmutableSet.builder();
802 portBuilder.add(port);
803 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
804 portBuilder.build(), nextObj.id()).addToExisting();
Charles Chanc91c8782016-03-30 17:54:24 -0700805 }
806 // Create, store and apply the new nextObj and fwdObj
Charles Chan72779502016-04-23 17:36:10 -0700807 ObjectiveContext context = new DefaultObjectiveContext(
808 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
809 mcastIp, deviceId, port.toLong(), assignedVlan),
810 (objective, error) ->
811 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
812 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Charles Chanc91c8782016-03-30 17:54:24 -0700813 ForwardingObjective fwdObj =
Charles Chan72779502016-04-23 17:36:10 -0700814 fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chanc91c8782016-03-30 17:54:24 -0700815 srManager.flowObjectiveService.next(deviceId, newNextObj);
816 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700817 }
818
819 /**
820 * Removes a port from given multicast group on given device.
821 * This involves the update of L3 multicast group and multicast routing
822 * table entry.
823 *
824 * @param deviceId device ID
825 * @param port port to be added
826 * @param mcastIp multicast group
827 * @param assignedVlan assigned VLAN ID
828 * @return true if this is the last sink on this device
829 */
830 private boolean removePortFromDevice(DeviceId deviceId, PortNumber port,
831 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700832 McastStoreKey mcastStoreKey =
833 new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700834 // This device is not serving this multicast group
Charles Chan72779502016-04-23 17:36:10 -0700835 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700836 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
837 return false;
838 }
Charles Chan72779502016-04-23 17:36:10 -0700839 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700840
841 Set<PortNumber> existingPorts = getPorts(nextObj.next());
Charles Chan72779502016-04-23 17:36:10 -0700842 // This port does not serve this multicast group
Charles Chanc91c8782016-03-30 17:54:24 -0700843 if (!existingPorts.contains(port)) {
844 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
845 return false;
846 }
847 // Copy and modify the ImmutableSet
848 existingPorts = Sets.newHashSet(existingPorts);
849 existingPorts.remove(port);
850
851 NextObjective newNextObj;
Pier Luigi8cd46de2018-01-19 10:24:53 +0100852 ObjectiveContext context;
Charles Chanc91c8782016-03-30 17:54:24 -0700853 ForwardingObjective fwdObj;
854 if (existingPorts.isEmpty()) {
Pier Luigi8cd46de2018-01-19 10:24:53 +0100855 // If this is the last sink, remove flows and last bucket
Charles Chanc91c8782016-03-30 17:54:24 -0700856 // NOTE: Rely on GroupStore garbage collection rather than explicitly
857 // remove L3MG since there might be other flows/groups refer to
858 // the same L2IG
Pier Luigi8cd46de2018-01-19 10:24:53 +0100859 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700860 (objective) -> log.debug("Successfully remove {} on {}/{}, vlan {}",
861 mcastIp, deviceId, port.toLong(), assignedVlan),
862 (objective, error) ->
863 log.warn("Failed to remove {} on {}/{}, vlan {}: {}",
864 mcastIp, deviceId, port.toLong(), assignedVlan, error));
865 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
866 mcastNextObjStore.remove(mcastStoreKey);
Charles Chanc91c8782016-03-30 17:54:24 -0700867 } else {
868 // If this is not the last sink, update flows and groups
Pier Luigi8cd46de2018-01-19 10:24:53 +0100869 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700870 (objective) -> log.debug("Successfully update {} on {}/{}, vlan {}",
871 mcastIp, deviceId, port.toLong(), assignedVlan),
872 (objective, error) ->
873 log.warn("Failed to update {} on {}/{}, vlan {}: {}",
874 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier Luigi8cd46de2018-01-19 10:24:53 +0100875 // Here we store the next objective with the remaining port
876 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
877 existingPorts, nextObj.id()).removeFromExisting();
Charles Chan82f19972016-05-17 13:13:55 -0700878 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chan72779502016-04-23 17:36:10 -0700879 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700880 }
Pier Luigi8cd46de2018-01-19 10:24:53 +0100881 // Let's modify the next objective removing the bucket
882 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
883 ImmutableSet.of(port), nextObj.id()).removeFromExisting();
884 srManager.flowObjectiveService.next(deviceId, newNextObj);
885 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700886 return existingPorts.isEmpty();
887 }
888
Charles Chan72779502016-04-23 17:36:10 -0700889 /**
890 * Removes entire group on given device.
891 *
892 * @param deviceId device ID
893 * @param mcastIp multicast group to be removed
894 * @param assignedVlan assigned VLAN ID
895 */
896 private void removeGroupFromDevice(DeviceId deviceId, IpAddress mcastIp,
897 VlanId assignedVlan) {
898 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
899 // This device is not serving this multicast group
900 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
901 log.warn("{} is not serving {}. Abort.", deviceId, mcastIp);
902 return;
903 }
904 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
905 // NOTE: Rely on GroupStore garbage collection rather than explicitly
906 // remove L3MG since there might be other flows/groups refer to
907 // the same L2IG
908 ObjectiveContext context = new DefaultObjectiveContext(
909 (objective) -> log.debug("Successfully remove {} on {}, vlan {}",
910 mcastIp, deviceId, assignedVlan),
911 (objective, error) ->
912 log.warn("Failed to remove {} on {}, vlan {}: {}",
913 mcastIp, deviceId, assignedVlan, error));
914 ForwardingObjective fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
915 srManager.flowObjectiveService.forward(deviceId, fwdObj);
916 mcastNextObjStore.remove(mcastStoreKey);
917 mcastRoleStore.remove(mcastStoreKey);
918 }
919
Pier Luigi580fd8a2018-01-16 10:47:50 +0100920 private void installPath(IpAddress mcastIp, ConnectPoint source, Path mcastPath) {
921 // Get Links
922 List<Link> links = mcastPath.links();
Pier1a7e0c02018-03-12 15:00:54 -0700923
924 // Setup new ingress mcast role
925 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).src().deviceId()),
926 INGRESS);
927
Pier Luigi580fd8a2018-01-16 10:47:50 +0100928 // For each link, modify the next on the source device adding the src port
929 // and a new filter objective on the destination port
930 links.forEach(link -> {
931 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
932 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
Pier979e61a2018-03-07 11:42:50 +0100933 addFilterToDevice(link.dst().deviceId(), link.dst().port(),
934 assignedVlan(null), mcastIp, null);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100935 });
Pier1a7e0c02018-03-12 15:00:54 -0700936
937 // Setup mcast role for the transit
938 links.stream()
939 .filter(link -> !link.src().deviceId().equals(source.deviceId()))
940 .forEach(link -> mcastRoleStore.put(new McastStoreKey(mcastIp, link.src().deviceId()),
941 TRANSIT));
Charles Chan72779502016-04-23 17:36:10 -0700942 }
943
Charles Chanc91c8782016-03-30 17:54:24 -0700944 /**
945 * Creates a next objective builder for multicast.
946 *
947 * @param mcastIp multicast group
948 * @param assignedVlan assigned VLAN ID
949 * @param outPorts set of output port numbers
950 * @return next objective builder
951 */
952 private NextObjective.Builder nextObjBuilder(IpAddress mcastIp,
Pier Luigi4f0dd212018-01-19 10:24:53 +0100953 VlanId assignedVlan, Set<PortNumber> outPorts, Integer nextId) {
954 // If nextId is null allocate a new one
955 if (nextId == null) {
956 nextId = srManager.flowObjectiveService.allocateNextId();
957 }
Charles Chanc91c8782016-03-30 17:54:24 -0700958
959 TrafficSelector metadata =
960 DefaultTrafficSelector.builder()
961 .matchVlanId(assignedVlan)
962 .matchIPDst(mcastIp.toIpPrefix())
963 .build();
964
965 NextObjective.Builder nextObjBuilder = DefaultNextObjective
966 .builder().withId(nextId)
Pier Luigi69f774d2018-02-28 12:10:50 +0100967 .withType(NextObjective.Type.BROADCAST).fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700968 .withMeta(metadata);
969
970 outPorts.forEach(port -> {
971 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
972 if (egressVlan().equals(VlanId.NONE)) {
973 tBuilder.popVlan();
974 }
975 tBuilder.setOutput(port);
976 nextObjBuilder.addTreatment(tBuilder.build());
977 });
978
979 return nextObjBuilder;
980 }
981
982 /**
983 * Creates a forwarding objective builder for multicast.
984 *
985 * @param mcastIp multicast group
986 * @param assignedVlan assigned VLAN ID
987 * @param nextId next ID of the L3 multicast group
988 * @return forwarding objective builder
989 */
990 private ForwardingObjective.Builder fwdObjBuilder(IpAddress mcastIp,
991 VlanId assignedVlan, int nextId) {
992 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000993 IpPrefix mcastPrefix = mcastIp.toIpPrefix();
994
995 if (mcastIp.isIp4()) {
996 sbuilder.matchEthType(Ethernet.TYPE_IPV4);
997 sbuilder.matchIPDst(mcastPrefix);
998 } else {
999 sbuilder.matchEthType(Ethernet.TYPE_IPV6);
1000 sbuilder.matchIPv6Dst(mcastPrefix);
1001 }
1002
1003
Charles Chanc91c8782016-03-30 17:54:24 -07001004 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
1005 metabuilder.matchVlanId(assignedVlan);
1006
1007 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder();
1008 fwdBuilder.withSelector(sbuilder.build())
1009 .withMeta(metabuilder.build())
1010 .nextStep(nextId)
1011 .withFlag(ForwardingObjective.Flag.SPECIFIC)
Pier Luigi69f774d2018-02-28 12:10:50 +01001012 .fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -07001013 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1014 return fwdBuilder;
1015 }
1016
1017 /**
1018 * Creates a filtering objective builder for multicast.
1019 *
Charles Chanc91c8782016-03-30 17:54:24 -07001020 * @param ingressPort ingress port of the multicast stream
1021 * @param assignedVlan assigned VLAN ID
Charles Chanf909e5b2018-03-02 13:26:22 -08001022 * @param routerMac router MAC. This is carried in metadata and used from some switches that
1023 * need to put unicast entry before multicast entry in TMAC table.
Charles Chanc91c8782016-03-30 17:54:24 -07001024 * @return filtering objective builder
1025 */
Charles Chan958ce892018-03-02 15:41:41 -08001026 private FilteringObjective.Builder filterObjBuilder(PortNumber ingressPort,
Pier979e61a2018-03-07 11:42:50 +01001027 VlanId assignedVlan, IpAddress mcastIp, MacAddress routerMac, McastRole mcastRole) {
Charles Chanc91c8782016-03-30 17:54:24 -07001028 FilteringObjective.Builder filtBuilder = DefaultFilteringObjective.builder();
Pier979e61a2018-03-07 11:42:50 +01001029 // Let's add the in port matching and the priority
1030 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
1031 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1032 // According to the mcast role we match on the proper vlan
1033 // If the role is null we are on the transit or on the egress
1034 if (mcastRole == null) {
1035 filtBuilder.addCondition(Criteria.matchVlanId(egressVlan()));
Julia Fergusonf1d9c342017-08-10 18:15:24 +00001036 } else {
Pier979e61a2018-03-07 11:42:50 +01001037 filtBuilder.addCondition(Criteria.matchVlanId(ingressVlan()));
Julia Fergusonf1d9c342017-08-10 18:15:24 +00001038 }
Pier979e61a2018-03-07 11:42:50 +01001039 // According to the IP type we set the proper match on the mac address
1040 if (mcastIp.isIp4()) {
1041 filtBuilder.addCondition(Criteria.matchEthDstMasked(MacAddress.IPV4_MULTICAST,
1042 MacAddress.IPV4_MULTICAST_MASK));
1043 } else {
1044 filtBuilder.addCondition(Criteria.matchEthDstMasked(MacAddress.IPV6_MULTICAST,
1045 MacAddress.IPV6_MULTICAST_MASK));
1046 }
1047 // We finally build the meta treatment
Charles Chan0932eca2016-06-28 16:50:13 -07001048 TrafficTreatment tt = DefaultTrafficTreatment.builder()
Charles Chanf909e5b2018-03-02 13:26:22 -08001049 .pushVlan().setVlanId(assignedVlan)
1050 .setEthDst(routerMac)
1051 .build();
Charles Chan0932eca2016-06-28 16:50:13 -07001052 filtBuilder.withMeta(tt);
Pier979e61a2018-03-07 11:42:50 +01001053 // Done, we return a permit filtering objective
Pier Luigi69f774d2018-02-28 12:10:50 +01001054 return filtBuilder.permit().fromApp(srManager.appId());
Charles Chanc91c8782016-03-30 17:54:24 -07001055 }
1056
1057 /**
1058 * Gets output ports information from treatments.
1059 *
1060 * @param treatments collection of traffic treatments
1061 * @return set of output port numbers
1062 */
1063 private Set<PortNumber> getPorts(Collection<TrafficTreatment> treatments) {
1064 ImmutableSet.Builder<PortNumber> builder = ImmutableSet.builder();
1065 treatments.forEach(treatment -> {
1066 treatment.allInstructions().stream()
1067 .filter(instr -> instr instanceof OutputInstruction)
1068 .forEach(instr -> {
1069 builder.add(((OutputInstruction) instr).port());
1070 });
1071 });
1072 return builder.build();
1073 }
1074
Pier Luigi51ee7c02018-02-23 19:57:40 +01001075 // Utility method to verify is a link is a pair-link
1076 private boolean isPairLink(Link link) {
1077 // Take src id, src port, dst id and dst port
1078 final DeviceId srcId = link.src().deviceId();
1079 final PortNumber srcPort = link.src().port();
1080 final DeviceId dstId = link.dst().deviceId();
1081 final PortNumber dstPort = link.dst().port();
1082 // init as true
1083 boolean isPairLink = true;
1084 try {
1085 // If one of this condition is not true; it is not a pair link
Pier Luigi69f774d2018-02-28 12:10:50 +01001086 if (!(srManager.deviceConfiguration().isEdgeDevice(srcId) &&
1087 srManager.deviceConfiguration().isEdgeDevice(dstId) &&
1088 srManager.deviceConfiguration().getPairDeviceId(srcId).equals(dstId) &&
1089 srManager.deviceConfiguration().getPairLocalPort(srcId).equals(srcPort) &&
1090 srManager.deviceConfiguration().getPairLocalPort(dstId).equals(dstPort))) {
Pier Luigi51ee7c02018-02-23 19:57:40 +01001091 isPairLink = false;
1092 }
1093 } catch (DeviceConfigNotFoundException e) {
1094 // Configuration not provided
1095 log.warn("Could not check if the link {} is pairlink "
1096 + "config not yet provided", link);
1097 isPairLink = false;
1098 }
1099 return isPairLink;
1100 }
1101
Charles Chanc91c8782016-03-30 17:54:24 -07001102 /**
1103 * Gets a path from src to dst.
1104 * If a path was allocated before, returns the allocated path.
1105 * Otherwise, randomly pick one from available paths.
1106 *
1107 * @param src source device ID
1108 * @param dst destination device ID
1109 * @param mcastIp multicast group
1110 * @return an optional path from src to dst
1111 */
1112 private Optional<Path> getPath(DeviceId src, DeviceId dst, IpAddress mcastIp) {
Pier Luigid8a15162018-02-15 16:33:08 +01001113 // Takes a snapshot of the topology
1114 final Topology currentTopology = topologyService.currentTopology();
Charles Chanc91c8782016-03-30 17:54:24 -07001115 List<Path> allPaths = Lists.newArrayList(
Pier Luigid8a15162018-02-15 16:33:08 +01001116 topologyService.getPaths(currentTopology, src, dst)
1117 );
Pier Luigi51ee7c02018-02-23 19:57:40 +01001118 // Create list of valid paths
1119 allPaths.removeIf(path -> path.links().stream().anyMatch(this::isPairLink));
1120 // If there are no valid paths, just exit
Charles Chan72779502016-04-23 17:36:10 -07001121 log.debug("{} path(s) found from {} to {}", allPaths.size(), src, dst);
Charles Chanc91c8782016-03-30 17:54:24 -07001122 if (allPaths.isEmpty()) {
Charles Chanc91c8782016-03-30 17:54:24 -07001123 return Optional.empty();
1124 }
1125
Pier Luigi91573e12018-01-23 16:06:38 +01001126 // Create a map index of suitablity-to-list of paths. For example
1127 // a path in the list associated to the index 1 shares only the
1128 // first hop and it is less suitable of a path belonging to the index
1129 // 2 that shares leaf-spine.
1130 Map<Integer, List<Path>> eligiblePaths = Maps.newHashMap();
1131 // Some init steps
1132 int nhop;
1133 McastStoreKey mcastStoreKey;
1134 Link hop;
1135 PortNumber srcPort;
1136 Set<PortNumber> existingPorts;
1137 NextObjective nextObj;
1138 // Iterate over paths looking for eligible paths
1139 for (Path path : allPaths) {
1140 // Unlikely, it will happen...
1141 if (!src.equals(path.links().get(0).src().deviceId())) {
1142 continue;
1143 }
1144 nhop = 0;
1145 // Iterate over the links
1146 while (nhop < path.links().size()) {
1147 // Get the link and verify if a next related
1148 // to the src device exist in the store
1149 hop = path.links().get(nhop);
1150 mcastStoreKey = new McastStoreKey(mcastIp, hop.src().deviceId());
1151 // It does not exist in the store, exit
1152 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1153 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001154 }
Pier Luigi91573e12018-01-23 16:06:38 +01001155 // Get the output ports on the next
1156 nextObj = mcastNextObjStore.get(mcastStoreKey).value();
1157 existingPorts = getPorts(nextObj.next());
1158 // And the src port on the link
1159 srcPort = hop.src().port();
1160 // the src port is not used as output, exit
1161 if (!existingPorts.contains(srcPort)) {
1162 break;
1163 }
1164 nhop++;
1165 }
1166 // n_hop defines the index
1167 if (nhop > 0) {
1168 eligiblePaths.compute(nhop, (index, paths) -> {
1169 paths = paths == null ? Lists.newArrayList() : paths;
1170 paths.add(path);
1171 return paths;
1172 });
Charles Chanc91c8782016-03-30 17:54:24 -07001173 }
1174 }
Pier Luigi91573e12018-01-23 16:06:38 +01001175
1176 // No suitable paths
1177 if (eligiblePaths.isEmpty()) {
1178 log.debug("No eligiblePath(s) found from {} to {}", src, dst);
1179 // Otherwise, randomly pick a path
1180 Collections.shuffle(allPaths);
1181 return allPaths.stream().findFirst();
1182 }
1183
1184 // Let's take the best ones
1185 Integer bestIndex = eligiblePaths.keySet()
1186 .stream()
1187 .sorted(Comparator.reverseOrder())
1188 .findFirst().orElse(null);
1189 List<Path> bestPaths = eligiblePaths.get(bestIndex);
1190 log.debug("{} eligiblePath(s) found from {} to {}",
1191 bestPaths.size(), src, dst);
1192 // randomly pick a path on the highest index
1193 Collections.shuffle(bestPaths);
1194 return bestPaths.stream().findFirst();
Charles Chanc91c8782016-03-30 17:54:24 -07001195 }
1196
1197 /**
Charles Chan72779502016-04-23 17:36:10 -07001198 * Gets device(s) of given role in given multicast group.
1199 *
1200 * @param mcastIp multicast IP
1201 * @param role multicast role
1202 * @return set of device ID or empty set if not found
1203 */
1204 private Set<DeviceId> getDevice(IpAddress mcastIp, McastRole role) {
1205 return mcastRoleStore.entrySet().stream()
1206 .filter(entry -> entry.getKey().mcastIp().equals(mcastIp) &&
1207 entry.getValue().value() == role)
1208 .map(Map.Entry::getKey).map(McastStoreKey::deviceId)
1209 .collect(Collectors.toSet());
1210 }
1211
1212 /**
Charles Chana8f9dee2016-05-16 18:44:13 -07001213 * Gets source connect point of given multicast group.
1214 *
1215 * @param mcastIp multicast IP
1216 * @return source connect point or null if not found
1217 */
1218 private ConnectPoint getSource(IpAddress mcastIp) {
1219 return srManager.multicastRouteService.getRoutes().stream()
1220 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1221 .map(mcastRoute -> srManager.multicastRouteService.fetchSource(mcastRoute))
1222 .findAny().orElse(null);
1223 }
Pier Luigi92e69be2018-03-02 12:53:37 +01001224 /**
1225 * Gets sinks of given multicast group.
1226 *
1227 * @param mcastIp multicast IP
1228 * @return set of sinks or empty set if not found
1229 */
1230 private Set<ConnectPoint> getSinks(IpAddress mcastIp) {
1231 return srManager.multicastRouteService.getRoutes().stream()
1232 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1233 .map(mcastRoute -> srManager.multicastRouteService.fetchSinks(mcastRoute))
1234 .findAny().orElse(Collections.emptySet());
1235 }
Charles Chana8f9dee2016-05-16 18:44:13 -07001236
1237 /**
Charles Chan72779502016-04-23 17:36:10 -07001238 * Gets groups which is affected by the link down event.
1239 *
1240 * @param link link going down
1241 * @return a set of multicast IpAddress
1242 */
1243 private Set<IpAddress> getAffectedGroups(Link link) {
1244 DeviceId deviceId = link.src().deviceId();
1245 PortNumber port = link.src().port();
1246 return mcastNextObjStore.entrySet().stream()
1247 .filter(entry -> entry.getKey().deviceId().equals(deviceId) &&
1248 getPorts(entry.getValue().value().next()).contains(port))
1249 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1250 .collect(Collectors.toSet());
1251 }
1252
1253 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001254 * Gets groups which are affected by the device down event.
1255 *
1256 * @param deviceId device going down
1257 * @return a set of multicast IpAddress
1258 */
1259 private Set<IpAddress> getAffectedGroups(DeviceId deviceId) {
1260 return mcastNextObjStore.entrySet().stream()
1261 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
1262 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1263 .collect(Collectors.toSet());
1264 }
1265
1266 /**
Pier979e61a2018-03-07 11:42:50 +01001267 * Gets ingress VLAN from McastConfig.
1268 *
1269 * @return ingress VLAN or VlanId.NONE if not configured
1270 */
1271 private VlanId ingressVlan() {
1272 McastConfig mcastConfig =
1273 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1274 return (mcastConfig != null) ? mcastConfig.ingressVlan() : VlanId.NONE;
1275 }
1276
1277 /**
Charles Chanc91c8782016-03-30 17:54:24 -07001278 * Gets egress VLAN from McastConfig.
1279 *
1280 * @return egress VLAN or VlanId.NONE if not configured
1281 */
1282 private VlanId egressVlan() {
1283 McastConfig mcastConfig =
1284 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1285 return (mcastConfig != null) ? mcastConfig.egressVlan() : VlanId.NONE;
1286 }
1287
1288 /**
1289 * Gets assigned VLAN according to the value of egress VLAN.
Charles Chana8f9dee2016-05-16 18:44:13 -07001290 * If connect point is specified, try to reuse the assigned VLAN on the connect point.
Charles Chanc91c8782016-03-30 17:54:24 -07001291 *
Charles Chana8f9dee2016-05-16 18:44:13 -07001292 * @param cp connect point; Can be null if not specified
1293 * @return assigned VLAN ID
Charles Chanc91c8782016-03-30 17:54:24 -07001294 */
Charles Chana8f9dee2016-05-16 18:44:13 -07001295 private VlanId assignedVlan(ConnectPoint cp) {
1296 // Use the egressVlan if it is tagged
1297 if (!egressVlan().equals(VlanId.NONE)) {
1298 return egressVlan();
1299 }
1300 // Reuse unicast VLAN if the port has subnet configured
1301 if (cp != null) {
Charles Chanf9759582017-10-20 19:09:16 -07001302 VlanId untaggedVlan = srManager.getInternalVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001303 return (untaggedVlan != null) ? untaggedVlan : INTERNAL_VLAN;
Charles Chana8f9dee2016-05-16 18:44:13 -07001304 }
Charles Chan10b0fb72017-02-02 16:20:42 -08001305 // Use DEFAULT_VLAN if none of the above matches
1306 return SegmentRoutingManager.INTERNAL_VLAN;
Charles Chanc91c8782016-03-30 17:54:24 -07001307 }
Charles Chan72779502016-04-23 17:36:10 -07001308
1309 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +01001310 * Gets assigned VLAN according to the value in the meta.
1311 *
1312 * @param nextObjective nextObjective to analyze
1313 * @return assigned VLAN ID
1314 */
1315 private VlanId assignedVlanFromNext(NextObjective nextObjective) {
1316 return ((VlanIdCriterion) nextObjective.meta().getCriterion(VLAN_VID)).vlanId();
1317 }
1318
1319 /**
Charles Chan72779502016-04-23 17:36:10 -07001320 * Gets the spine-facing port on ingress device of given multicast group.
1321 *
1322 * @param mcastIp multicast IP
1323 * @return spine-facing port on ingress device
1324 */
Pier1a7e0c02018-03-12 15:00:54 -07001325 private Set<PortNumber> ingressTransitPort(IpAddress mcastIp) {
Pier979e61a2018-03-07 11:42:50 +01001326 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Charles Chan72779502016-04-23 17:36:10 -07001327 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -07001328 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Charles Chan72779502016-04-23 17:36:10 -07001329 if (ingressDevice != null) {
1330 NextObjective nextObj = mcastNextObjStore
1331 .get(new McastStoreKey(mcastIp, ingressDevice)).value();
1332 Set<PortNumber> ports = getPorts(nextObj.next());
Pier1a7e0c02018-03-12 15:00:54 -07001333 // Let's find out all the ingress-transit ports
Charles Chan72779502016-04-23 17:36:10 -07001334 for (PortNumber port : ports) {
1335 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001336 if (srManager.deviceConfiguration() != null &&
1337 srManager.deviceConfiguration().getPortSubnets(ingressDevice, port).isEmpty() &&
Charles Chan82f19972016-05-17 13:13:55 -07001338 !srManager.xConnectHandler.hasXConnect(new ConnectPoint(ingressDevice, port))) {
Pier1a7e0c02018-03-12 15:00:54 -07001339 portBuilder.add(port);
Charles Chan72779502016-04-23 17:36:10 -07001340 }
1341 }
1342 }
Pier1a7e0c02018-03-12 15:00:54 -07001343 return portBuilder.build();
Charles Chan72779502016-04-23 17:36:10 -07001344 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001345
1346 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001347 * Verify if the given device has sinks
1348 * for the multicast group.
1349 *
1350 * @param deviceId device Id
1351 * @param mcastIp multicast IP
1352 * @return true if the device has sink for the group.
1353 * False otherwise.
1354 */
1355 private boolean hasSinks(DeviceId deviceId, IpAddress mcastIp) {
1356 if (deviceId != null) {
1357 // Get the nextobjective
1358 Versioned<NextObjective> versionedNextObj = mcastNextObjStore.get(
1359 new McastStoreKey(mcastIp, deviceId)
1360 );
1361 // If it exists
1362 if (versionedNextObj != null) {
1363 NextObjective nextObj = versionedNextObj.value();
1364 // Retrieves all the output ports
1365 Set<PortNumber> ports = getPorts(nextObj.next());
1366 // Tries to find at least one port that is not spine-facing
1367 for (PortNumber port : ports) {
1368 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001369 if (srManager.deviceConfiguration() != null &&
1370 (!srManager.deviceConfiguration().getPortSubnets(deviceId, port).isEmpty() ||
Pier Luigi580fd8a2018-01-16 10:47:50 +01001371 srManager.xConnectHandler.hasXConnect(new ConnectPoint(deviceId, port)))) {
1372 return true;
1373 }
1374 }
1375 }
1376 }
1377 return false;
1378 }
1379
1380 /**
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001381 * Removes filtering objective for given device and port.
1382 *
1383 * @param deviceId device ID
1384 * @param port ingress port number
1385 * @param assignedVlan assigned VLAN ID
1386 * @param mcastIp multicast IP address
1387 */
Pier979e61a2018-03-07 11:42:50 +01001388 private void removeFilterToDevice(DeviceId deviceId, PortNumber port,
1389 VlanId assignedVlan, IpAddress mcastIp, McastRole mcastRole) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001390 // Do nothing if the port is configured as suppressed
1391 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
1392 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +01001393 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001394 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
1395 log.info("Ignore suppressed port {}", connectPoint);
1396 return;
1397 }
1398
Charles Chanf909e5b2018-03-02 13:26:22 -08001399 MacAddress routerMac;
1400 try {
1401 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
1402 } catch (DeviceConfigNotFoundException dcnfe) {
1403 log.warn("Fail to push filtering objective since device is not configured. Abort");
1404 return;
1405 }
1406
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001407 FilteringObjective.Builder filtObjBuilder =
Pier979e61a2018-03-07 11:42:50 +01001408 filterObjBuilder(port, assignedVlan, mcastIp, routerMac, mcastRole);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001409 ObjectiveContext context = new DefaultObjectiveContext(
1410 (objective) -> log.debug("Successfully removed filter on {}/{}, vlan {}",
1411 deviceId, port.toLong(), assignedVlan),
1412 (objective, error) ->
1413 log.warn("Failed to remove filter on {}/{}, vlan {}: {}",
1414 deviceId, port.toLong(), assignedVlan, error));
1415 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.remove(context));
1416 }
1417
1418 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +01001419 * Updates filtering objective for given device and port.
1420 * It is called in general when the mcast config has been
1421 * changed.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001422 *
1423 * @param deviceId device ID
1424 * @param portNum ingress port number
1425 * @param vlanId assigned VLAN ID
1426 * @param install true to add, false to remove
1427 */
Pier Luigi69f774d2018-02-28 12:10:50 +01001428 public void updateFilterToDevice(DeviceId deviceId, PortNumber portNum,
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001429 VlanId vlanId, boolean install) {
Pier Luigi35dab3f2018-01-25 16:16:02 +01001430 lastMcastChange = Instant.now();
1431 mcastLock();
1432 try {
1433 // Iterates over the route and updates properly the filtering objective
1434 // on the source device.
1435 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
1436 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
1437 if (source.deviceId().equals(deviceId) && source.port().equals(portNum)) {
1438 if (install) {
Pier979e61a2018-03-07 11:42:50 +01001439 addFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001440 } else {
Pier979e61a2018-03-07 11:42:50 +01001441 removeFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), null);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001442 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001443 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001444 });
1445 } finally {
1446 mcastUnlock();
1447 }
1448 }
1449
Pier Luigi6786b922018-02-02 16:19:11 +01001450 private boolean isLeader(ConnectPoint source) {
1451 // Continue only when we have the mastership on the operation
1452 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1453 // When the source is available we just check the mastership
1454 if (srManager.deviceService.isAvailable(source.deviceId())) {
1455 return false;
1456 }
1457 // Fallback with Leadership service
1458 // source id is used a topic
1459 NodeId leader = srManager.leadershipService.runForLeadership(
1460 source.deviceId().toString()).leaderNodeId();
1461 // Verify if this node is the leader
1462 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1463 return false;
1464 }
1465 }
1466 // Done
1467 return true;
1468 }
1469
Pier Luigi35dab3f2018-01-25 16:16:02 +01001470 /**
1471 * Performs bucket verification operation for all mcast groups in the devices.
1472 * Firstly, it verifies that mcast is stable before trying verification operation.
1473 * Verification consists in creating new nexts with VERIFY operation. Actually,
1474 * the operation is totally delegated to the driver.
1475 */
1476 private final class McastBucketCorrector implements Runnable {
1477
1478 @Override
1479 public void run() {
1480 // Verify if the Mcast has been stable for MCAST_STABLITY_THRESHOLD
1481 if (!isMcastStable()) {
1482 return;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001483 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001484 // Acquires lock
1485 mcastLock();
1486 try {
1487 // Iterates over the routes and verify the related next objectives
1488 srManager.multicastRouteService.getRoutes()
1489 .stream()
1490 .map(McastRoute::group)
1491 .forEach(mcastIp -> {
1492 log.trace("Running mcast buckets corrector for mcast group: {}",
1493 mcastIp);
1494
1495 // For each group we get current information in the store
1496 // and issue a check of the next objectives in place
Pier979e61a2018-03-07 11:42:50 +01001497 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +01001498 .stream().findAny().orElse(null);
Pier1a7e0c02018-03-12 15:00:54 -07001499 Set<DeviceId> transitDevices = getDevice(mcastIp, TRANSIT);
Pier979e61a2018-03-07 11:42:50 +01001500 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi92e69be2018-03-02 12:53:37 +01001501 // Get source and sinks from Mcast Route Service and warn about errors
Pier Luigi35dab3f2018-01-25 16:16:02 +01001502 ConnectPoint source = getSource(mcastIp);
Pier Luigi92e69be2018-03-02 12:53:37 +01001503 Set<ConnectPoint> sinks = getSinks(mcastIp);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001504
1505 // Do not proceed if ingress device or source of this group are missing
1506 if (ingressDevice == null || source == null) {
Pier Luigi92e69be2018-03-02 12:53:37 +01001507 if (!sinks.isEmpty()) {
1508 log.warn("Unable to run buckets corrector. " +
1509 "Missing ingress {} or source {} for group {}",
1510 ingressDevice, source, mcastIp);
1511 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001512 return;
1513 }
1514
1515 // Continue only when this instance is the master of source device
1516 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1517 log.trace("Unable to run buckets corrector. " +
1518 "Skip {} due to lack of mastership " +
1519 "of the source device {}",
1520 mcastIp, source.deviceId());
1521 return;
1522 }
1523
1524 // Create the set of the devices to be processed
1525 ImmutableSet.Builder<DeviceId> devicesBuilder = ImmutableSet.builder();
1526 devicesBuilder.add(ingressDevice);
Pier1a7e0c02018-03-12 15:00:54 -07001527 if (!transitDevices.isEmpty()) {
1528 devicesBuilder.addAll(transitDevices);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001529 }
1530 if (!egressDevices.isEmpty()) {
1531 devicesBuilder.addAll(egressDevices);
1532 }
1533 Set<DeviceId> devicesToProcess = devicesBuilder.build();
1534
1535 // Iterate over the devices
1536 devicesToProcess.forEach(deviceId -> {
1537 McastStoreKey currentKey = new McastStoreKey(mcastIp, deviceId);
1538 // If next exists in our store verify related next objective
1539 if (mcastNextObjStore.containsKey(currentKey)) {
1540 NextObjective currentNext = mcastNextObjStore.get(currentKey).value();
1541 // Get current ports
1542 Set<PortNumber> currentPorts = getPorts(currentNext.next());
1543 // Rebuild the next objective
1544 currentNext = nextObjBuilder(
1545 mcastIp,
1546 assignedVlan(deviceId.equals(source.deviceId()) ? source : null),
1547 currentPorts,
1548 currentNext.id()
1549 ).verify();
1550 // Send to the flowobjective service
1551 srManager.flowObjectiveService.next(deviceId, currentNext);
1552 } else {
Pier Luigid8a15162018-02-15 16:33:08 +01001553 log.warn("Unable to run buckets corrector. " +
Pier Luigi35dab3f2018-01-25 16:16:02 +01001554 "Missing next for {} and group {}",
1555 deviceId, mcastIp);
1556 }
1557 });
1558
1559 });
1560 } finally {
1561 // Finally, it releases the lock
1562 mcastUnlock();
1563 }
1564
1565 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001566 }
Pier Luigi0f9635b2018-01-15 18:06:43 +01001567
1568 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
1569 // If mcast ip is present
1570 if (mcastIp != null) {
1571 return mcastNextObjStore.entrySet().stream()
1572 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1573 .collect(Collectors.toMap(Map.Entry::getKey,
1574 entry -> entry.getValue().value().id()));
1575 }
1576 // Otherwise take all the groups
1577 return mcastNextObjStore.entrySet().stream()
1578 .collect(Collectors.toMap(Map.Entry::getKey,
1579 entry -> entry.getValue().value().id()));
1580 }
1581
Pier Luigi69f774d2018-02-28 12:10:50 +01001582 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +01001583 // If mcast ip is present
1584 if (mcastIp != null) {
1585 return mcastRoleStore.entrySet().stream()
1586 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1587 .collect(Collectors.toMap(Map.Entry::getKey,
1588 entry -> entry.getValue().value()));
1589 }
1590 // Otherwise take all the groups
1591 return mcastRoleStore.entrySet().stream()
1592 .collect(Collectors.toMap(Map.Entry::getKey,
1593 entry -> entry.getValue().value()));
1594 }
1595
1596 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
1597 Map<ConnectPoint, List<ConnectPoint>> mcastPaths = Maps.newHashMap();
1598 // Get the source
1599 ConnectPoint source = getSource(mcastIp);
1600 // Source cannot be null, we don't know the starting point
1601 if (source != null) {
1602 // Init steps
1603 Set<DeviceId> visited = Sets.newHashSet();
1604 List<ConnectPoint> currentPath = Lists.newArrayList(
1605 source
1606 );
1607 // Build recursively the mcast paths
1608 buildMcastPaths(source.deviceId(), visited, mcastPaths, currentPath, mcastIp);
1609 }
1610 return mcastPaths;
1611 }
1612
1613 private void buildMcastPaths(DeviceId toVisit, Set<DeviceId> visited,
1614 Map<ConnectPoint, List<ConnectPoint>> mcastPaths,
1615 List<ConnectPoint> currentPath, IpAddress mcastIp) {
1616 // If we have visited the node to visit
1617 // there is a loop
1618 if (visited.contains(toVisit)) {
1619 return;
1620 }
1621 // Visit next-hop
1622 visited.add(toVisit);
1623 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, toVisit);
1624 // Looking for next-hops
1625 if (mcastNextObjStore.containsKey(mcastStoreKey)) {
1626 // Build egress connectpoints
1627 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
1628 // Get Ports
1629 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
1630 // Build relative cps
1631 ImmutableSet.Builder<ConnectPoint> cpBuilder = ImmutableSet.builder();
1632 outputPorts.forEach(portNumber -> cpBuilder.add(new ConnectPoint(toVisit, portNumber)));
1633 Set<ConnectPoint> egressPoints = cpBuilder.build();
1634 // Define other variables for the next steps
1635 Set<Link> egressLinks;
1636 List<ConnectPoint> newCurrentPath;
1637 Set<DeviceId> newVisited;
1638 DeviceId newToVisit;
1639 for (ConnectPoint egressPoint : egressPoints) {
1640 egressLinks = srManager.linkService.getEgressLinks(egressPoint);
1641 // If it does not have egress links, stop
1642 if (egressLinks.isEmpty()) {
1643 // Add the connect points to the path
1644 newCurrentPath = Lists.newArrayList(currentPath);
1645 newCurrentPath.add(0, egressPoint);
1646 // Save in the map
1647 mcastPaths.put(egressPoint, newCurrentPath);
1648 } else {
1649 newVisited = Sets.newHashSet(visited);
1650 // Iterate over the egress links for the next hops
1651 for (Link egressLink : egressLinks) {
1652 // Update to visit
1653 newToVisit = egressLink.dst().deviceId();
1654 // Add the connect points to the path
1655 newCurrentPath = Lists.newArrayList(currentPath);
1656 newCurrentPath.add(0, egressPoint);
1657 newCurrentPath.add(0, egressLink.dst());
1658 // Go to the next hop
1659 buildMcastPaths(newToVisit, newVisited, mcastPaths, newCurrentPath, mcastIp);
1660 }
1661 }
1662 }
1663 }
1664 }
1665
Charles Chanc91c8782016-03-30 17:54:24 -07001666}