blob: d35d25326a11fbaee8cbb23bbc218fa96c67f039 [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;
Pier979e61a2018-03-07 11:42:50 +010097import static org.onosproject.segmentrouting.mcast.McastRole.EGRESS;
98import static org.onosproject.segmentrouting.mcast.McastRole.INGRESS;
99import static org.onosproject.segmentrouting.mcast.McastRole.TRANSIT;
Charles Chanc91c8782016-03-30 17:54:24 -0700100
101/**
Pier Luigi69f774d2018-02-28 12:10:50 +0100102 * Handles Multicast related events.
Charles Chanc91c8782016-03-30 17:54:24 -0700103 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700104public class McastHandler {
105 private static final Logger log = LoggerFactory.getLogger(McastHandler.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700106 private final SegmentRoutingManager srManager;
107 private final ApplicationId coreAppId;
Charles Chan82f19972016-05-17 13:13:55 -0700108 private final StorageService storageService;
109 private final TopologyService topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700110 private final ConsistentMap<McastStoreKey, NextObjective> mcastNextObjStore;
111 private final KryoNamespace.Builder mcastKryo;
112 private final ConsistentMap<McastStoreKey, McastRole> mcastRoleStore;
113
Pier Luigid29ca7c2018-02-28 17:24:03 +0100114 // Wait time for the cache
115 private static final int WAIT_TIME_MS = 1000;
116 /**
117 * The mcastEventCache is implemented to avoid race condition by giving more time to the
118 * underlying subsystems to process previous calls.
119 */
120 private Cache<McastCacheKey, McastEvent> mcastEventCache = CacheBuilder.newBuilder()
121 .expireAfterWrite(WAIT_TIME_MS, TimeUnit.MILLISECONDS)
122 .removalListener((RemovalNotification<McastCacheKey, McastEvent> notification) -> {
123 // Get group ip, sink and related event
124 IpAddress mcastIp = notification.getKey().mcastIp();
125 ConnectPoint sink = notification.getKey().sink();
126 McastEvent mcastEvent = notification.getValue();
127 RemovalCause cause = notification.getCause();
128 log.debug("mcastEventCache removal event. group={}, sink={}, mcastEvent={}, cause={}",
129 mcastIp, sink, mcastEvent, cause);
130 // If it expires or it has been replaced, we deque the event
131 switch (notification.getCause()) {
132 case REPLACED:
133 case EXPIRED:
134 dequeueMcastEvent(mcastEvent);
135 break;
136 default:
137 break;
138 }
139 }).build();
140
141 private void enqueueMcastEvent(McastEvent mcastEvent) {
142 log.debug("Enqueue mcastEvent {}", mcastEvent);
143 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
144 // Let's create the keys of the cache
145 ImmutableSet.Builder<ConnectPoint> sinksBuilder = ImmutableSet.builder();
146 // For this event we will have a set of sinks
147 if (mcastEvent.type() == SOURCE_ADDED ||
148 mcastEvent.type() == SOURCE_UPDATED ||
149 mcastEvent.type() == ROUTE_REMOVED) {
150 // Add all the sinks
151 sinksBuilder.addAll(mcastRouteInfo.sinks());
152 } else {
153 // We have just one sink in this case
154 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
155 // It is always true, unless something of bad happened
156 // in the mcast route store
157 if (sink != null) {
158 sinksBuilder.add(sink);
159 }
160 }
161 // Push the elements in the cache
162 sinksBuilder.build().forEach(sink -> {
163 McastCacheKey cacheKey = new McastCacheKey(mcastRouteInfo.route().group(),
164 sink);
165 mcastEventCache.put(cacheKey, mcastEvent);
166 });
167 }
168
169 private void dequeueMcastEvent(McastEvent mcastEvent) {
170 log.debug("Dequeue mcastEvent {}", mcastEvent);
171 final McastRouteInfo mcastRouteInfo = mcastEvent.subject();
172 // Get source, mcast group
173 ConnectPoint source = mcastRouteInfo.source().orElse(null);
174 IpAddress mcastIp = mcastRouteInfo.route().group();
175 // According to the event type let's call the proper method
176 switch (mcastEvent.type()) {
177 case SOURCE_ADDED:
178 // Get all the sinks and process
179 Set<ConnectPoint> sinks = mcastRouteInfo.sinks();
180 sinks.forEach(sink -> processSinkAddedInternal(source, sink, mcastIp));
181 break;
182 case SOURCE_UPDATED:
183 // Get old source
184 ConnectPoint oldSource = mcastEvent.prevSubject().source().orElse(null);
185 // Just the first cached element will be processed
186 processSourceUpdatedInternal(mcastIp, source, oldSource);
187 break;
188 case ROUTE_REMOVED:
189 // Process the route removed, just the first cached element will be processed
190 processRouteRemovedInternal(source, mcastIp);
191 break;
192 case SINK_ADDED:
193 // Get the only sink and process
194 ConnectPoint sink = mcastRouteInfo.sink().orElse(null);
195 processSinkAddedInternal(source, sink, mcastIp);
196 break;
197 case SINK_REMOVED:
198 sink = mcastRouteInfo.sink().orElse(null);
199 processSinkRemovedInternal(source, sink, mcastIp);
200 break;
201 default:
202 break;
203 }
204 }
205
Pier Luigi35dab3f2018-01-25 16:16:02 +0100206 // Mcast lock to serialize local operations
207 private final Lock mcastLock = new ReentrantLock();
208
209 /**
210 * Acquires the lock used when making mcast changes.
211 */
212 private void mcastLock() {
213 mcastLock.lock();
214 }
215
216 /**
217 * Releases the lock used when making mcast changes.
218 */
219 private void mcastUnlock() {
220 mcastLock.unlock();
221 }
222
223 // Stability threshold for Mcast. Seconds
224 private static final long MCAST_STABLITY_THRESHOLD = 5;
225 // Last change done
226 private Instant lastMcastChange = Instant.now();
227
228 /**
229 * Determines if mcast in the network has been stable in the last
230 * MCAST_STABLITY_THRESHOLD seconds, by comparing the current time
231 * to the last mcast change timestamp.
232 *
233 * @return true if stable
234 */
235 private boolean isMcastStable() {
236 long last = (long) (lastMcastChange.toEpochMilli() / 1000.0);
237 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das97241862018-02-14 14:14:54 -0800238 log.trace("Mcast stable since {}s", now - last);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100239 return (now - last) > MCAST_STABLITY_THRESHOLD;
240 }
241
242 // Verify interval for Mcast
243 private static final long MCAST_VERIFY_INTERVAL = 30;
244
245 // Executor for mcast bucket corrector
246 private ScheduledExecutorService executorService
Pier Luigid29ca7c2018-02-28 17:24:03 +0100247 = newScheduledThreadPool(1, groupedThreads("mcastWorker", "mcastWorker-%d", log));
Pier Luigi35dab3f2018-01-25 16:16:02 +0100248
Charles Chan72779502016-04-23 17:36:10 -0700249 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700250 * Constructs the McastEventHandler.
251 *
252 * @param srManager Segment Routing manager
253 */
Charles Chan1eaf4802016-04-18 13:44:03 -0700254 public McastHandler(SegmentRoutingManager srManager) {
Charles Chanc91c8782016-03-30 17:54:24 -0700255 coreAppId = srManager.coreService.getAppId(CoreService.CORE_APP_NAME);
Charles Chanc91c8782016-03-30 17:54:24 -0700256 this.srManager = srManager;
257 this.storageService = srManager.storageService;
258 this.topologyService = srManager.topologyService;
Charles Chan72779502016-04-23 17:36:10 -0700259 mcastKryo = new KryoNamespace.Builder()
Charles Chanc91c8782016-03-30 17:54:24 -0700260 .register(KryoNamespaces.API)
Charles Chan72779502016-04-23 17:36:10 -0700261 .register(McastStoreKey.class)
262 .register(McastRole.class);
Charles Chanc91c8782016-03-30 17:54:24 -0700263 mcastNextObjStore = storageService
Charles Chan72779502016-04-23 17:36:10 -0700264 .<McastStoreKey, NextObjective>consistentMapBuilder()
Charles Chanc91c8782016-03-30 17:54:24 -0700265 .withName("onos-mcast-nextobj-store")
Charles Chan4922a172016-05-23 16:45:45 -0700266 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-NextObj")))
Charles Chanc91c8782016-03-30 17:54:24 -0700267 .build();
Charles Chan72779502016-04-23 17:36:10 -0700268 mcastRoleStore = storageService
269 .<McastStoreKey, McastRole>consistentMapBuilder()
270 .withName("onos-mcast-role-store")
Charles Chan4922a172016-05-23 16:45:45 -0700271 .withSerializer(Serializer.using(mcastKryo.build("McastHandler-Role")))
Charles Chan72779502016-04-23 17:36:10 -0700272 .build();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100273 // Init the executor service and the buckets corrector
274 executorService.scheduleWithFixedDelay(new McastBucketCorrector(), 10,
275 MCAST_VERIFY_INTERVAL,
276 TimeUnit.SECONDS);
Pier Luigid29ca7c2018-02-28 17:24:03 +0100277 // Schedule the clean up, this will allow the processing of the expired events
278 executorService.scheduleAtFixedRate(mcastEventCache::cleanUp, 0,
279 WAIT_TIME_MS, TimeUnit.MILLISECONDS);
Charles Chan72779502016-04-23 17:36:10 -0700280 }
281
282 /**
283 * Read initial multicast from mcast store.
284 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100285 public void init() {
Charles Chan72779502016-04-23 17:36:10 -0700286 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
287 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
288 Set<ConnectPoint> sinks = srManager.multicastRouteService.fetchSinks(mcastRoute);
289 sinks.forEach(sink -> {
290 processSinkAddedInternal(source, sink, mcastRoute.group());
291 });
292 });
Charles Chanc91c8782016-03-30 17:54:24 -0700293 }
294
295 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +0100296 * Clean up when deactivating the application.
297 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100298 public void terminate() {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100299 executorService.shutdown();
300 }
301
302 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +0100303 * Processes the SOURCE_ADDED, SOURCE_UPDATED, SINK_ADDED,
304 * SINK_REMOVED and ROUTE_REMOVED events.
Charles Chanc91c8782016-03-30 17:54:24 -0700305 *
306 * @param event McastEvent with SOURCE_ADDED type
307 */
Pier Luigid29ca7c2018-02-28 17:24:03 +0100308 public void processMcastEvent(McastEvent event) {
309 log.info("process {}", event);
310 // Verify if it is a complete event
Charles Chanc91c8782016-03-30 17:54:24 -0700311 McastRouteInfo mcastRouteInfo = event.subject();
312 if (!mcastRouteInfo.isComplete()) {
Pier Luigid29ca7c2018-02-28 17:24:03 +0100313 log.info("Incompleted McastRouteInfo. Abort {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -0700314 return;
315 }
Pier Luigid29ca7c2018-02-28 17:24:03 +0100316 // Just enqueue for now
317 enqueueMcastEvent(event);
Pier Luigi6786b922018-02-02 16:19:11 +0100318 }
319
320 /**
Pier Luigie80d6b42018-02-26 12:31:38 +0100321 * Process the SOURCE_UPDATED event.
322 *
323 * @param newSource the updated srouce info
324 * @param oldSource the outdated source info
325 */
326 private void processSourceUpdatedInternal(IpAddress mcastIp,
327 ConnectPoint newSource,
328 ConnectPoint oldSource) {
329 lastMcastChange = Instant.now();
330 mcastLock();
331 try {
332 log.debug("Processing source updated for group {}", mcastIp);
333
334 // Build key for the store and retrieve old data
335 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, oldSource.deviceId());
336
337 // Verify leadership on the operation
338 if (!isLeader(oldSource)) {
339 log.debug("Skip {} due to lack of leadership", mcastIp);
340 return;
341 }
342
343 // This device is not serving this multicast group
344 if (!mcastRoleStore.containsKey(mcastStoreKey) ||
345 !mcastNextObjStore.containsKey(mcastStoreKey)) {
346 log.warn("{} is not serving {}. Abort.", oldSource.deviceId(), mcastIp);
347 return;
348 }
349 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
350 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
351
Pier Luigid29ca7c2018-02-28 17:24:03 +0100352 // This an optimization to avoid unnecessary removal and add
353 if (!assignedVlanFromNext(nextObjective).equals(assignedVlan(newSource))) {
354 // Let's remove old flows and groups
355 removeGroupFromDevice(oldSource.deviceId(), mcastIp, assignedVlan(oldSource));
356 // Push new flows and group
357 outputPorts.forEach(portNumber -> addPortToDevice(newSource.deviceId(), portNumber,
358 mcastIp, assignedVlan(newSource)));
359 }
Pier Luigie80d6b42018-02-26 12:31:38 +0100360 addFilterToDevice(newSource.deviceId(), newSource.port(),
Pier979e61a2018-03-07 11:42:50 +0100361 assignedVlan(newSource), mcastIp, INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100362 // Setup mcast roles
363 mcastRoleStore.put(new McastStoreKey(mcastIp, newSource.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100364 INGRESS);
Pier Luigie80d6b42018-02-26 12:31:38 +0100365 } finally {
366 mcastUnlock();
367 }
368 }
369
370 /**
Pier Luigi6786b922018-02-02 16:19:11 +0100371 * Removes the entire mcast tree related to this group.
372 *
373 * @param mcastIp multicast group IP address
374 */
375 private void processRouteRemovedInternal(ConnectPoint source, IpAddress mcastIp) {
376 lastMcastChange = Instant.now();
377 mcastLock();
378 try {
Pier Luigie80d6b42018-02-26 12:31:38 +0100379 log.debug("Processing route removed for group {}", mcastIp);
Pier Luigi6786b922018-02-02 16:19:11 +0100380
381 // Find out the ingress, transit and egress device of the affected group
Pier979e61a2018-03-07 11:42:50 +0100382 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi6786b922018-02-02 16:19:11 +0100383 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100384 DeviceId transitDevice = getDevice(mcastIp, TRANSIT)
Pier Luigi6786b922018-02-02 16:19:11 +0100385 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100386 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi6786b922018-02-02 16:19:11 +0100387
388 // Verify leadership on the operation
389 if (!isLeader(source)) {
390 log.debug("Skip {} due to lack of leadership", mcastIp);
391 return;
392 }
393
394 // If there are egress devices, sinks could be only on the ingress
395 if (!egressDevices.isEmpty()) {
396 egressDevices.forEach(
397 deviceId -> removeGroupFromDevice(deviceId, mcastIp, assignedVlan(null))
398 );
399 }
400 // Transit could be null
401 if (transitDevice != null) {
402 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
403 }
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();
517 checkState(links.size() == 2,
518 "Path in leaf-spine topology should always be two hops: ", links);
Charles Chan72779502016-04-23 17:36:10 -0700519
Pier Luigi35dab3f2018-01-25 16:16:02 +0100520 links.forEach(link -> {
521 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
522 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
Pier979e61a2018-03-07 11:42:50 +0100523 addFilterToDevice(link.dst().deviceId(), link.dst().port(),
524 assignedVlan(null), mcastIp, null);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100525 });
526
527 // Process the egress device
528 addPortToDevice(sink.deviceId(), sink.port(), mcastIp, assignedVlan(null));
529
530 // Setup mcast roles
531 mcastRoleStore.put(new McastStoreKey(mcastIp, source.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100532 INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100533 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100534 TRANSIT);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100535 mcastRoleStore.put(new McastStoreKey(mcastIp, sink.deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100536 EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100537 } else {
538 log.warn("Unable to find a path from {} to {}. Abort sinkAdded",
539 source.deviceId(), sink.deviceId());
540 }
541 } finally {
542 mcastUnlock();
Charles Chanc91c8782016-03-30 17:54:24 -0700543 }
544 }
545
546 /**
Charles Chan72779502016-04-23 17:36:10 -0700547 * Processes the LINK_DOWN event.
548 *
549 * @param affectedLink Link that is going down
550 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100551 public void processLinkDown(Link affectedLink) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100552 lastMcastChange = Instant.now();
553 mcastLock();
554 try {
555 // Get groups affected by the link down event
556 getAffectedGroups(affectedLink).forEach(mcastIp -> {
557 // TODO Optimize when the group editing is in place
558 log.debug("Processing link down {} for group {}",
559 affectedLink, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100560
Pier Luigi35dab3f2018-01-25 16:16:02 +0100561 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100562 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100563 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100564 DeviceId transitDevice = getDevice(mcastIp, TRANSIT)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100565 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100566 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100567 ConnectPoint source = getSource(mcastIp);
Charles Chana8f9dee2016-05-16 18:44:13 -0700568
Pier Luigi35dab3f2018-01-25 16:16:02 +0100569 // Do not proceed if any of these info is missing
570 if (ingressDevice == null || transitDevice == null
571 || egressDevices == null || source == null) {
572 log.warn("Missing ingress {}, transit {}, egress {} devices or source {}",
573 ingressDevice, transitDevice, egressDevices, source);
574 return;
Charles Chan72779502016-04-23 17:36:10 -0700575 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100576
577 // Continue only when this instance is the master of source device
578 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
579 log.debug("Skip {} due to lack of mastership of the source device {}",
580 source.deviceId());
581 return;
582 }
583
584 // Remove entire transit
585 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
586
587 // Remove transit-facing port on ingress device
588 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
589 if (ingressTransitPort != null) {
Pier Luigi92e69be2018-03-02 12:53:37 +0100590 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
591 mcastIp, assignedVlan(source));
592 if (isLast) {
593 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
594 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100595 }
596
597 // Construct a new path for each egress device
598 egressDevices.forEach(egressDevice -> {
599 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
600 if (mcastPath.isPresent()) {
601 installPath(mcastIp, source, mcastPath.get());
602 } else {
603 log.warn("Fail to recover egress device {} from link failure {}",
604 egressDevice, affectedLink);
605 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
606 }
607 });
Charles Chan72779502016-04-23 17:36:10 -0700608 });
Pier Luigi35dab3f2018-01-25 16:16:02 +0100609 } finally {
610 mcastUnlock();
611 }
Charles Chan72779502016-04-23 17:36:10 -0700612 }
613
614 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +0100615 * Process the DEVICE_DOWN event.
616 *
617 * @param deviceDown device going down
618 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100619 public void processDeviceDown(DeviceId deviceDown) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100620 lastMcastChange = Instant.now();
621 mcastLock();
622 try {
623 // Get the mcast groups affected by the device going down
624 getAffectedGroups(deviceDown).forEach(mcastIp -> {
625 // TODO Optimize when the group editing is in place
626 log.debug("Processing device down {} for group {}",
627 deviceDown, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100628
Pier Luigi35dab3f2018-01-25 16:16:02 +0100629 // Find out the ingress, transit and egress device of affected group
Pier979e61a2018-03-07 11:42:50 +0100630 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100631 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100632 DeviceId transitDevice = getDevice(mcastIp, TRANSIT)
Pier Luigi35dab3f2018-01-25 16:16:02 +0100633 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +0100634 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +0100635 ConnectPoint source = getSource(mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100636
Pier Luigi35dab3f2018-01-25 16:16:02 +0100637 // Do not proceed if ingress device or source of this group are missing
638 // If sinks are in other leafs, we have ingress, transit, egress, and source
639 // If sinks are in the same leaf, we have just ingress and source
640 if (ingressDevice == null || source == null) {
641 log.warn("Missing ingress {} or source {} for group {}",
642 ingressDevice, source, mcastIp);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100643 return;
644 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100645
Pier Luigi6786b922018-02-02 16:19:11 +0100646 // Verify leadership on the operation
647 if (!isLeader(source)) {
648 log.debug("Skip {} due to lack of leadership", mcastIp);
649 return;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100650 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100651
652 // If it exists, we have to remove it in any case
653 if (transitDevice != null) {
654 // Remove entire transit
655 removeGroupFromDevice(transitDevice, mcastIp, assignedVlan(null));
656 }
657 // If the ingress is down
658 if (ingressDevice.equals(deviceDown)) {
659 // Remove entire ingress
660 removeGroupFromDevice(ingressDevice, mcastIp, assignedVlan(source));
661 // If other sinks different from the ingress exist
662 if (!egressDevices.isEmpty()) {
663 // Remove all the remaining egress
664 egressDevices.forEach(
665 egressDevice -> removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null))
666 );
Pier Luigi580fd8a2018-01-16 10:47:50 +0100667 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100668 } else {
669 // Egress or transit could be down at this point
670 // Get the ingress-transit port if it exists
671 PortNumber ingressTransitPort = ingressTransitPort(mcastIp);
672 if (ingressTransitPort != null) {
673 // Remove transit-facing port on ingress device
Pier Luigi92e69be2018-03-02 12:53:37 +0100674 boolean isLast = removePortFromDevice(ingressDevice, ingressTransitPort,
675 mcastIp, assignedVlan(source));
676 // There are no further ports
677 if (isLast) {
678 // Remove entire ingress
679 mcastRoleStore.remove(new McastStoreKey(mcastIp, ingressDevice));
680 }
Pier Luigi35dab3f2018-01-25 16:16:02 +0100681 }
682 // One of the egress device is down
683 if (egressDevices.contains(deviceDown)) {
684 // Remove entire device down
685 removeGroupFromDevice(deviceDown, mcastIp, assignedVlan(null));
686 // Remove the device down from egress
687 egressDevices.remove(deviceDown);
688 // If there are no more egress and ingress does not have sinks
689 if (egressDevices.isEmpty() && !hasSinks(ingressDevice, mcastIp)) {
Pier Luigi35dab3f2018-01-25 16:16:02 +0100690 // We have done
691 return;
692 }
693 }
694 // Construct a new path for each egress device
695 egressDevices.forEach(egressDevice -> {
696 Optional<Path> mcastPath = getPath(ingressDevice, egressDevice, mcastIp);
697 // If there is a new path
698 if (mcastPath.isPresent()) {
699 // Let's install the new mcast path for this egress
700 installPath(mcastIp, source, mcastPath.get());
701 } else {
702 // We were not able to find an alternative path for this egress
703 log.warn("Fail to recover egress device {} from device down {}",
704 egressDevice, deviceDown);
705 removeGroupFromDevice(egressDevice, mcastIp, assignedVlan(null));
706 }
707 });
708 }
709 });
710 } finally {
711 mcastUnlock();
712 }
Pier Luigi580fd8a2018-01-16 10:47:50 +0100713 }
714
715 /**
Charles Chanc91c8782016-03-30 17:54:24 -0700716 * Adds filtering objective for given device and port.
717 *
718 * @param deviceId device ID
719 * @param port ingress port number
720 * @param assignedVlan assigned VLAN ID
721 */
Pier979e61a2018-03-07 11:42:50 +0100722 private void addFilterToDevice(DeviceId deviceId, PortNumber port,
723 VlanId assignedVlan, IpAddress mcastIp, McastRole mcastRole) {
Charles Chanc91c8782016-03-30 17:54:24 -0700724 // Do nothing if the port is configured as suppressed
Charles Chan370a65b2016-05-10 17:29:47 -0700725 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
726 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +0100727 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Charles Chan370a65b2016-05-10 17:29:47 -0700728 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
729 log.info("Ignore suppressed port {}", connectPoint);
Charles Chanc91c8782016-03-30 17:54:24 -0700730 return;
731 }
732
Charles Chanf909e5b2018-03-02 13:26:22 -0800733 MacAddress routerMac;
734 try {
735 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
736 } catch (DeviceConfigNotFoundException dcnfe) {
737 log.warn("Fail to push filtering objective since device is not configured. Abort");
738 return;
739 }
740
Charles Chanc91c8782016-03-30 17:54:24 -0700741 FilteringObjective.Builder filtObjBuilder =
Pier979e61a2018-03-07 11:42:50 +0100742 filterObjBuilder(port, assignedVlan, mcastIp, routerMac, mcastRole);
Charles Chan72779502016-04-23 17:36:10 -0700743 ObjectiveContext context = new DefaultObjectiveContext(
744 (objective) -> log.debug("Successfully add filter on {}/{}, vlan {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800745 deviceId, port.toLong(), assignedVlan),
Charles Chan72779502016-04-23 17:36:10 -0700746 (objective, error) ->
747 log.warn("Failed to add filter on {}/{}, vlan {}: {}",
Charles Chan10b0fb72017-02-02 16:20:42 -0800748 deviceId, port.toLong(), assignedVlan, error));
Charles Chan72779502016-04-23 17:36:10 -0700749 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.add(context));
Charles Chanc91c8782016-03-30 17:54:24 -0700750 }
751
752 /**
753 * Adds a port to given multicast group on given device. This involves the
754 * update of L3 multicast group and multicast routing table entry.
755 *
756 * @param deviceId device ID
757 * @param port port to be added
758 * @param mcastIp multicast group
759 * @param assignedVlan assigned VLAN ID
760 */
761 private void addPortToDevice(DeviceId deviceId, PortNumber port,
762 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700763 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700764 ImmutableSet.Builder<PortNumber> portBuilder = ImmutableSet.builder();
Pier Luigi4f0dd212018-01-19 10:24:53 +0100765 NextObjective newNextObj;
Charles Chan72779502016-04-23 17:36:10 -0700766 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700767 // First time someone request this mcast group via this device
768 portBuilder.add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100769 // New nextObj
770 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
771 portBuilder.build(), null).add();
772 // Store the new port
773 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700774 } else {
775 // This device already serves some subscribers of this mcast group
Charles Chan72779502016-04-23 17:36:10 -0700776 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700777 // Stop if the port is already in the nextobj
778 Set<PortNumber> existingPorts = getPorts(nextObj.next());
779 if (existingPorts.contains(port)) {
780 log.info("NextObj for {}/{} already exists. Abort", deviceId, port);
781 return;
782 }
Pier Luigi4f0dd212018-01-19 10:24:53 +0100783 // Let's add the port and reuse the previous one
Yuta HIGUCHIbef07b52018-02-09 18:05:23 -0800784 portBuilder.addAll(existingPorts).add(port);
Pier Luigi4f0dd212018-01-19 10:24:53 +0100785 // Reuse previous nextObj
786 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
787 portBuilder.build(), nextObj.id()).addToExisting();
788 // Store the final next objective and send only the difference to the driver
789 mcastNextObjStore.put(mcastStoreKey, newNextObj);
790 // Add just the new port
791 portBuilder = ImmutableSet.builder();
792 portBuilder.add(port);
793 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
794 portBuilder.build(), nextObj.id()).addToExisting();
Charles Chanc91c8782016-03-30 17:54:24 -0700795 }
796 // Create, store and apply the new nextObj and fwdObj
Charles Chan72779502016-04-23 17:36:10 -0700797 ObjectiveContext context = new DefaultObjectiveContext(
798 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
799 mcastIp, deviceId, port.toLong(), assignedVlan),
800 (objective, error) ->
801 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
802 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Charles Chanc91c8782016-03-30 17:54:24 -0700803 ForwardingObjective fwdObj =
Charles Chan72779502016-04-23 17:36:10 -0700804 fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chanc91c8782016-03-30 17:54:24 -0700805 srManager.flowObjectiveService.next(deviceId, newNextObj);
806 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700807 }
808
809 /**
810 * Removes a port from given multicast group on given device.
811 * This involves the update of L3 multicast group and multicast routing
812 * table entry.
813 *
814 * @param deviceId device ID
815 * @param port port to be added
816 * @param mcastIp multicast group
817 * @param assignedVlan assigned VLAN ID
818 * @return true if this is the last sink on this device
819 */
820 private boolean removePortFromDevice(DeviceId deviceId, PortNumber port,
821 IpAddress mcastIp, VlanId assignedVlan) {
Charles Chan72779502016-04-23 17:36:10 -0700822 McastStoreKey mcastStoreKey =
823 new McastStoreKey(mcastIp, deviceId);
Charles Chanc91c8782016-03-30 17:54:24 -0700824 // This device is not serving this multicast group
Charles Chan72779502016-04-23 17:36:10 -0700825 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
Charles Chanc91c8782016-03-30 17:54:24 -0700826 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
827 return false;
828 }
Charles Chan72779502016-04-23 17:36:10 -0700829 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
Charles Chanc91c8782016-03-30 17:54:24 -0700830
831 Set<PortNumber> existingPorts = getPorts(nextObj.next());
Charles Chan72779502016-04-23 17:36:10 -0700832 // This port does not serve this multicast group
Charles Chanc91c8782016-03-30 17:54:24 -0700833 if (!existingPorts.contains(port)) {
834 log.warn("{} is not serving {} on port {}. Abort.", deviceId, mcastIp, port);
835 return false;
836 }
837 // Copy and modify the ImmutableSet
838 existingPorts = Sets.newHashSet(existingPorts);
839 existingPorts.remove(port);
840
841 NextObjective newNextObj;
Pier Luigi8cd46de2018-01-19 10:24:53 +0100842 ObjectiveContext context;
Charles Chanc91c8782016-03-30 17:54:24 -0700843 ForwardingObjective fwdObj;
844 if (existingPorts.isEmpty()) {
Pier Luigi8cd46de2018-01-19 10:24:53 +0100845 // If this is the last sink, remove flows and last bucket
Charles Chanc91c8782016-03-30 17:54:24 -0700846 // NOTE: Rely on GroupStore garbage collection rather than explicitly
847 // remove L3MG since there might be other flows/groups refer to
848 // the same L2IG
Pier Luigi8cd46de2018-01-19 10:24:53 +0100849 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700850 (objective) -> log.debug("Successfully remove {} on {}/{}, vlan {}",
851 mcastIp, deviceId, port.toLong(), assignedVlan),
852 (objective, error) ->
853 log.warn("Failed to remove {} on {}/{}, vlan {}: {}",
854 mcastIp, deviceId, port.toLong(), assignedVlan, error));
855 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
856 mcastNextObjStore.remove(mcastStoreKey);
Charles Chanc91c8782016-03-30 17:54:24 -0700857 } else {
858 // If this is not the last sink, update flows and groups
Pier Luigi8cd46de2018-01-19 10:24:53 +0100859 context = new DefaultObjectiveContext(
Charles Chan72779502016-04-23 17:36:10 -0700860 (objective) -> log.debug("Successfully update {} on {}/{}, vlan {}",
861 mcastIp, deviceId, port.toLong(), assignedVlan),
862 (objective, error) ->
863 log.warn("Failed to update {} on {}/{}, vlan {}: {}",
864 mcastIp, deviceId, port.toLong(), assignedVlan, error));
Pier Luigi8cd46de2018-01-19 10:24:53 +0100865 // Here we store the next objective with the remaining port
866 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
867 existingPorts, nextObj.id()).removeFromExisting();
Charles Chan82f19972016-05-17 13:13:55 -0700868 fwdObj = fwdObjBuilder(mcastIp, assignedVlan, newNextObj.id()).add(context);
Charles Chan72779502016-04-23 17:36:10 -0700869 mcastNextObjStore.put(mcastStoreKey, newNextObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700870 }
Pier Luigi8cd46de2018-01-19 10:24:53 +0100871 // Let's modify the next objective removing the bucket
872 newNextObj = nextObjBuilder(mcastIp, assignedVlan,
873 ImmutableSet.of(port), nextObj.id()).removeFromExisting();
874 srManager.flowObjectiveService.next(deviceId, newNextObj);
875 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Charles Chanc91c8782016-03-30 17:54:24 -0700876 return existingPorts.isEmpty();
877 }
878
Charles Chan72779502016-04-23 17:36:10 -0700879 /**
880 * Removes entire group on given device.
881 *
882 * @param deviceId device ID
883 * @param mcastIp multicast group to be removed
884 * @param assignedVlan assigned VLAN ID
885 */
886 private void removeGroupFromDevice(DeviceId deviceId, IpAddress mcastIp,
887 VlanId assignedVlan) {
888 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, deviceId);
889 // This device is not serving this multicast group
890 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
891 log.warn("{} is not serving {}. Abort.", deviceId, mcastIp);
892 return;
893 }
894 NextObjective nextObj = mcastNextObjStore.get(mcastStoreKey).value();
895 // NOTE: Rely on GroupStore garbage collection rather than explicitly
896 // remove L3MG since there might be other flows/groups refer to
897 // the same L2IG
898 ObjectiveContext context = new DefaultObjectiveContext(
899 (objective) -> log.debug("Successfully remove {} on {}, vlan {}",
900 mcastIp, deviceId, assignedVlan),
901 (objective, error) ->
902 log.warn("Failed to remove {} on {}, vlan {}: {}",
903 mcastIp, deviceId, assignedVlan, error));
904 ForwardingObjective fwdObj = fwdObjBuilder(mcastIp, assignedVlan, nextObj.id()).remove(context);
905 srManager.flowObjectiveService.forward(deviceId, fwdObj);
906 mcastNextObjStore.remove(mcastStoreKey);
907 mcastRoleStore.remove(mcastStoreKey);
908 }
909
Pier Luigi580fd8a2018-01-16 10:47:50 +0100910 private void installPath(IpAddress mcastIp, ConnectPoint source, Path mcastPath) {
911 // Get Links
912 List<Link> links = mcastPath.links();
913 // For each link, modify the next on the source device adding the src port
914 // and a new filter objective on the destination port
915 links.forEach(link -> {
916 addPortToDevice(link.src().deviceId(), link.src().port(), mcastIp,
917 assignedVlan(link.src().deviceId().equals(source.deviceId()) ? source : null));
Pier979e61a2018-03-07 11:42:50 +0100918 addFilterToDevice(link.dst().deviceId(), link.dst().port(),
919 assignedVlan(null), mcastIp, null);
Pier Luigi580fd8a2018-01-16 10:47:50 +0100920 });
921 // Setup new transit mcast role
922 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).dst().deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100923 TRANSIT);
Pier Luigi92e69be2018-03-02 12:53:37 +0100924 // Setup new ingress mcast role
925 mcastRoleStore.put(new McastStoreKey(mcastIp, links.get(0).src().deviceId()),
Pier979e61a2018-03-07 11:42:50 +0100926 INGRESS);
Charles Chan72779502016-04-23 17:36:10 -0700927 }
928
Charles Chanc91c8782016-03-30 17:54:24 -0700929 /**
930 * Creates a next objective builder for multicast.
931 *
932 * @param mcastIp multicast group
933 * @param assignedVlan assigned VLAN ID
934 * @param outPorts set of output port numbers
935 * @return next objective builder
936 */
937 private NextObjective.Builder nextObjBuilder(IpAddress mcastIp,
Pier Luigi4f0dd212018-01-19 10:24:53 +0100938 VlanId assignedVlan, Set<PortNumber> outPorts, Integer nextId) {
939 // If nextId is null allocate a new one
940 if (nextId == null) {
941 nextId = srManager.flowObjectiveService.allocateNextId();
942 }
Charles Chanc91c8782016-03-30 17:54:24 -0700943
944 TrafficSelector metadata =
945 DefaultTrafficSelector.builder()
946 .matchVlanId(assignedVlan)
947 .matchIPDst(mcastIp.toIpPrefix())
948 .build();
949
950 NextObjective.Builder nextObjBuilder = DefaultNextObjective
951 .builder().withId(nextId)
Pier Luigi69f774d2018-02-28 12:10:50 +0100952 .withType(NextObjective.Type.BROADCAST).fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700953 .withMeta(metadata);
954
955 outPorts.forEach(port -> {
956 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
957 if (egressVlan().equals(VlanId.NONE)) {
958 tBuilder.popVlan();
959 }
960 tBuilder.setOutput(port);
961 nextObjBuilder.addTreatment(tBuilder.build());
962 });
963
964 return nextObjBuilder;
965 }
966
967 /**
968 * Creates a forwarding objective builder for multicast.
969 *
970 * @param mcastIp multicast group
971 * @param assignedVlan assigned VLAN ID
972 * @param nextId next ID of the L3 multicast group
973 * @return forwarding objective builder
974 */
975 private ForwardingObjective.Builder fwdObjBuilder(IpAddress mcastIp,
976 VlanId assignedVlan, int nextId) {
977 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
Julia Fergusonf1d9c342017-08-10 18:15:24 +0000978 IpPrefix mcastPrefix = mcastIp.toIpPrefix();
979
980 if (mcastIp.isIp4()) {
981 sbuilder.matchEthType(Ethernet.TYPE_IPV4);
982 sbuilder.matchIPDst(mcastPrefix);
983 } else {
984 sbuilder.matchEthType(Ethernet.TYPE_IPV6);
985 sbuilder.matchIPv6Dst(mcastPrefix);
986 }
987
988
Charles Chanc91c8782016-03-30 17:54:24 -0700989 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
990 metabuilder.matchVlanId(assignedVlan);
991
992 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder();
993 fwdBuilder.withSelector(sbuilder.build())
994 .withMeta(metabuilder.build())
995 .nextStep(nextId)
996 .withFlag(ForwardingObjective.Flag.SPECIFIC)
Pier Luigi69f774d2018-02-28 12:10:50 +0100997 .fromApp(srManager.appId())
Charles Chanc91c8782016-03-30 17:54:24 -0700998 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
999 return fwdBuilder;
1000 }
1001
1002 /**
1003 * Creates a filtering objective builder for multicast.
1004 *
Charles Chanc91c8782016-03-30 17:54:24 -07001005 * @param ingressPort ingress port of the multicast stream
1006 * @param assignedVlan assigned VLAN ID
Charles Chanf909e5b2018-03-02 13:26:22 -08001007 * @param routerMac router MAC. This is carried in metadata and used from some switches that
1008 * need to put unicast entry before multicast entry in TMAC table.
Charles Chanc91c8782016-03-30 17:54:24 -07001009 * @return filtering objective builder
1010 */
Charles Chan958ce892018-03-02 15:41:41 -08001011 private FilteringObjective.Builder filterObjBuilder(PortNumber ingressPort,
Pier979e61a2018-03-07 11:42:50 +01001012 VlanId assignedVlan, IpAddress mcastIp, MacAddress routerMac, McastRole mcastRole) {
Charles Chanc91c8782016-03-30 17:54:24 -07001013 FilteringObjective.Builder filtBuilder = DefaultFilteringObjective.builder();
Pier979e61a2018-03-07 11:42:50 +01001014 // Let's add the in port matching and the priority
1015 filtBuilder.withKey(Criteria.matchInPort(ingressPort))
1016 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1017 // According to the mcast role we match on the proper vlan
1018 // If the role is null we are on the transit or on the egress
1019 if (mcastRole == null) {
1020 filtBuilder.addCondition(Criteria.matchVlanId(egressVlan()));
Julia Fergusonf1d9c342017-08-10 18:15:24 +00001021 } else {
Pier979e61a2018-03-07 11:42:50 +01001022 filtBuilder.addCondition(Criteria.matchVlanId(ingressVlan()));
Julia Fergusonf1d9c342017-08-10 18:15:24 +00001023 }
Pier979e61a2018-03-07 11:42:50 +01001024 // According to the IP type we set the proper match on the mac address
1025 if (mcastIp.isIp4()) {
1026 filtBuilder.addCondition(Criteria.matchEthDstMasked(MacAddress.IPV4_MULTICAST,
1027 MacAddress.IPV4_MULTICAST_MASK));
1028 } else {
1029 filtBuilder.addCondition(Criteria.matchEthDstMasked(MacAddress.IPV6_MULTICAST,
1030 MacAddress.IPV6_MULTICAST_MASK));
1031 }
1032 // We finally build the meta treatment
Charles Chan0932eca2016-06-28 16:50:13 -07001033 TrafficTreatment tt = DefaultTrafficTreatment.builder()
Charles Chanf909e5b2018-03-02 13:26:22 -08001034 .pushVlan().setVlanId(assignedVlan)
1035 .setEthDst(routerMac)
1036 .build();
Charles Chan0932eca2016-06-28 16:50:13 -07001037 filtBuilder.withMeta(tt);
Pier979e61a2018-03-07 11:42:50 +01001038 // Done, we return a permit filtering objective
Pier Luigi69f774d2018-02-28 12:10:50 +01001039 return filtBuilder.permit().fromApp(srManager.appId());
Charles Chanc91c8782016-03-30 17:54:24 -07001040 }
1041
1042 /**
1043 * Gets output ports information from treatments.
1044 *
1045 * @param treatments collection of traffic treatments
1046 * @return set of output port numbers
1047 */
1048 private Set<PortNumber> getPorts(Collection<TrafficTreatment> treatments) {
1049 ImmutableSet.Builder<PortNumber> builder = ImmutableSet.builder();
1050 treatments.forEach(treatment -> {
1051 treatment.allInstructions().stream()
1052 .filter(instr -> instr instanceof OutputInstruction)
1053 .forEach(instr -> {
1054 builder.add(((OutputInstruction) instr).port());
1055 });
1056 });
1057 return builder.build();
1058 }
1059
Pier Luigi51ee7c02018-02-23 19:57:40 +01001060 // Utility method to verify is a link is a pair-link
1061 private boolean isPairLink(Link link) {
1062 // Take src id, src port, dst id and dst port
1063 final DeviceId srcId = link.src().deviceId();
1064 final PortNumber srcPort = link.src().port();
1065 final DeviceId dstId = link.dst().deviceId();
1066 final PortNumber dstPort = link.dst().port();
1067 // init as true
1068 boolean isPairLink = true;
1069 try {
1070 // If one of this condition is not true; it is not a pair link
Pier Luigi69f774d2018-02-28 12:10:50 +01001071 if (!(srManager.deviceConfiguration().isEdgeDevice(srcId) &&
1072 srManager.deviceConfiguration().isEdgeDevice(dstId) &&
1073 srManager.deviceConfiguration().getPairDeviceId(srcId).equals(dstId) &&
1074 srManager.deviceConfiguration().getPairLocalPort(srcId).equals(srcPort) &&
1075 srManager.deviceConfiguration().getPairLocalPort(dstId).equals(dstPort))) {
Pier Luigi51ee7c02018-02-23 19:57:40 +01001076 isPairLink = false;
1077 }
1078 } catch (DeviceConfigNotFoundException e) {
1079 // Configuration not provided
1080 log.warn("Could not check if the link {} is pairlink "
1081 + "config not yet provided", link);
1082 isPairLink = false;
1083 }
1084 return isPairLink;
1085 }
1086
Charles Chanc91c8782016-03-30 17:54:24 -07001087 /**
1088 * Gets a path from src to dst.
1089 * If a path was allocated before, returns the allocated path.
1090 * Otherwise, randomly pick one from available paths.
1091 *
1092 * @param src source device ID
1093 * @param dst destination device ID
1094 * @param mcastIp multicast group
1095 * @return an optional path from src to dst
1096 */
1097 private Optional<Path> getPath(DeviceId src, DeviceId dst, IpAddress mcastIp) {
Pier Luigid8a15162018-02-15 16:33:08 +01001098 // Takes a snapshot of the topology
1099 final Topology currentTopology = topologyService.currentTopology();
Charles Chanc91c8782016-03-30 17:54:24 -07001100 List<Path> allPaths = Lists.newArrayList(
Pier Luigid8a15162018-02-15 16:33:08 +01001101 topologyService.getPaths(currentTopology, src, dst)
1102 );
Pier Luigi51ee7c02018-02-23 19:57:40 +01001103 // Create list of valid paths
1104 allPaths.removeIf(path -> path.links().stream().anyMatch(this::isPairLink));
1105 // If there are no valid paths, just exit
Charles Chan72779502016-04-23 17:36:10 -07001106 log.debug("{} path(s) found from {} to {}", allPaths.size(), src, dst);
Charles Chanc91c8782016-03-30 17:54:24 -07001107 if (allPaths.isEmpty()) {
Charles Chanc91c8782016-03-30 17:54:24 -07001108 return Optional.empty();
1109 }
1110
Pier Luigi91573e12018-01-23 16:06:38 +01001111 // Create a map index of suitablity-to-list of paths. For example
1112 // a path in the list associated to the index 1 shares only the
1113 // first hop and it is less suitable of a path belonging to the index
1114 // 2 that shares leaf-spine.
1115 Map<Integer, List<Path>> eligiblePaths = Maps.newHashMap();
1116 // Some init steps
1117 int nhop;
1118 McastStoreKey mcastStoreKey;
1119 Link hop;
1120 PortNumber srcPort;
1121 Set<PortNumber> existingPorts;
1122 NextObjective nextObj;
1123 // Iterate over paths looking for eligible paths
1124 for (Path path : allPaths) {
1125 // Unlikely, it will happen...
1126 if (!src.equals(path.links().get(0).src().deviceId())) {
1127 continue;
1128 }
1129 nhop = 0;
1130 // Iterate over the links
1131 while (nhop < path.links().size()) {
1132 // Get the link and verify if a next related
1133 // to the src device exist in the store
1134 hop = path.links().get(nhop);
1135 mcastStoreKey = new McastStoreKey(mcastIp, hop.src().deviceId());
1136 // It does not exist in the store, exit
1137 if (!mcastNextObjStore.containsKey(mcastStoreKey)) {
1138 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001139 }
Pier Luigi91573e12018-01-23 16:06:38 +01001140 // Get the output ports on the next
1141 nextObj = mcastNextObjStore.get(mcastStoreKey).value();
1142 existingPorts = getPorts(nextObj.next());
1143 // And the src port on the link
1144 srcPort = hop.src().port();
1145 // the src port is not used as output, exit
1146 if (!existingPorts.contains(srcPort)) {
1147 break;
1148 }
1149 nhop++;
1150 }
1151 // n_hop defines the index
1152 if (nhop > 0) {
1153 eligiblePaths.compute(nhop, (index, paths) -> {
1154 paths = paths == null ? Lists.newArrayList() : paths;
1155 paths.add(path);
1156 return paths;
1157 });
Charles Chanc91c8782016-03-30 17:54:24 -07001158 }
1159 }
Pier Luigi91573e12018-01-23 16:06:38 +01001160
1161 // No suitable paths
1162 if (eligiblePaths.isEmpty()) {
1163 log.debug("No eligiblePath(s) found from {} to {}", src, dst);
1164 // Otherwise, randomly pick a path
1165 Collections.shuffle(allPaths);
1166 return allPaths.stream().findFirst();
1167 }
1168
1169 // Let's take the best ones
1170 Integer bestIndex = eligiblePaths.keySet()
1171 .stream()
1172 .sorted(Comparator.reverseOrder())
1173 .findFirst().orElse(null);
1174 List<Path> bestPaths = eligiblePaths.get(bestIndex);
1175 log.debug("{} eligiblePath(s) found from {} to {}",
1176 bestPaths.size(), src, dst);
1177 // randomly pick a path on the highest index
1178 Collections.shuffle(bestPaths);
1179 return bestPaths.stream().findFirst();
Charles Chanc91c8782016-03-30 17:54:24 -07001180 }
1181
1182 /**
Charles Chan72779502016-04-23 17:36:10 -07001183 * Gets device(s) of given role in given multicast group.
1184 *
1185 * @param mcastIp multicast IP
1186 * @param role multicast role
1187 * @return set of device ID or empty set if not found
1188 */
1189 private Set<DeviceId> getDevice(IpAddress mcastIp, McastRole role) {
1190 return mcastRoleStore.entrySet().stream()
1191 .filter(entry -> entry.getKey().mcastIp().equals(mcastIp) &&
1192 entry.getValue().value() == role)
1193 .map(Map.Entry::getKey).map(McastStoreKey::deviceId)
1194 .collect(Collectors.toSet());
1195 }
1196
1197 /**
Charles Chana8f9dee2016-05-16 18:44:13 -07001198 * Gets source connect point of given multicast group.
1199 *
1200 * @param mcastIp multicast IP
1201 * @return source connect point or null if not found
1202 */
1203 private ConnectPoint getSource(IpAddress mcastIp) {
1204 return srManager.multicastRouteService.getRoutes().stream()
1205 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1206 .map(mcastRoute -> srManager.multicastRouteService.fetchSource(mcastRoute))
1207 .findAny().orElse(null);
1208 }
Pier Luigi92e69be2018-03-02 12:53:37 +01001209 /**
1210 * Gets sinks of given multicast group.
1211 *
1212 * @param mcastIp multicast IP
1213 * @return set of sinks or empty set if not found
1214 */
1215 private Set<ConnectPoint> getSinks(IpAddress mcastIp) {
1216 return srManager.multicastRouteService.getRoutes().stream()
1217 .filter(mcastRoute -> mcastRoute.group().equals(mcastIp))
1218 .map(mcastRoute -> srManager.multicastRouteService.fetchSinks(mcastRoute))
1219 .findAny().orElse(Collections.emptySet());
1220 }
Charles Chana8f9dee2016-05-16 18:44:13 -07001221
1222 /**
Charles Chan72779502016-04-23 17:36:10 -07001223 * Gets groups which is affected by the link down event.
1224 *
1225 * @param link link going down
1226 * @return a set of multicast IpAddress
1227 */
1228 private Set<IpAddress> getAffectedGroups(Link link) {
1229 DeviceId deviceId = link.src().deviceId();
1230 PortNumber port = link.src().port();
1231 return mcastNextObjStore.entrySet().stream()
1232 .filter(entry -> entry.getKey().deviceId().equals(deviceId) &&
1233 getPorts(entry.getValue().value().next()).contains(port))
1234 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1235 .collect(Collectors.toSet());
1236 }
1237
1238 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001239 * Gets groups which are affected by the device down event.
1240 *
1241 * @param deviceId device going down
1242 * @return a set of multicast IpAddress
1243 */
1244 private Set<IpAddress> getAffectedGroups(DeviceId deviceId) {
1245 return mcastNextObjStore.entrySet().stream()
1246 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
1247 .map(Map.Entry::getKey).map(McastStoreKey::mcastIp)
1248 .collect(Collectors.toSet());
1249 }
1250
1251 /**
Pier979e61a2018-03-07 11:42:50 +01001252 * Gets ingress VLAN from McastConfig.
1253 *
1254 * @return ingress VLAN or VlanId.NONE if not configured
1255 */
1256 private VlanId ingressVlan() {
1257 McastConfig mcastConfig =
1258 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1259 return (mcastConfig != null) ? mcastConfig.ingressVlan() : VlanId.NONE;
1260 }
1261
1262 /**
Charles Chanc91c8782016-03-30 17:54:24 -07001263 * Gets egress VLAN from McastConfig.
1264 *
1265 * @return egress VLAN or VlanId.NONE if not configured
1266 */
1267 private VlanId egressVlan() {
1268 McastConfig mcastConfig =
1269 srManager.cfgService.getConfig(coreAppId, McastConfig.class);
1270 return (mcastConfig != null) ? mcastConfig.egressVlan() : VlanId.NONE;
1271 }
1272
1273 /**
1274 * Gets assigned VLAN according to the value of egress VLAN.
Charles Chana8f9dee2016-05-16 18:44:13 -07001275 * If connect point is specified, try to reuse the assigned VLAN on the connect point.
Charles Chanc91c8782016-03-30 17:54:24 -07001276 *
Charles Chana8f9dee2016-05-16 18:44:13 -07001277 * @param cp connect point; Can be null if not specified
1278 * @return assigned VLAN ID
Charles Chanc91c8782016-03-30 17:54:24 -07001279 */
Charles Chana8f9dee2016-05-16 18:44:13 -07001280 private VlanId assignedVlan(ConnectPoint cp) {
1281 // Use the egressVlan if it is tagged
1282 if (!egressVlan().equals(VlanId.NONE)) {
1283 return egressVlan();
1284 }
1285 // Reuse unicast VLAN if the port has subnet configured
1286 if (cp != null) {
Charles Chanf9759582017-10-20 19:09:16 -07001287 VlanId untaggedVlan = srManager.getInternalVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001288 return (untaggedVlan != null) ? untaggedVlan : INTERNAL_VLAN;
Charles Chana8f9dee2016-05-16 18:44:13 -07001289 }
Charles Chan10b0fb72017-02-02 16:20:42 -08001290 // Use DEFAULT_VLAN if none of the above matches
1291 return SegmentRoutingManager.INTERNAL_VLAN;
Charles Chanc91c8782016-03-30 17:54:24 -07001292 }
Charles Chan72779502016-04-23 17:36:10 -07001293
1294 /**
Pier Luigid29ca7c2018-02-28 17:24:03 +01001295 * Gets assigned VLAN according to the value in the meta.
1296 *
1297 * @param nextObjective nextObjective to analyze
1298 * @return assigned VLAN ID
1299 */
1300 private VlanId assignedVlanFromNext(NextObjective nextObjective) {
1301 return ((VlanIdCriterion) nextObjective.meta().getCriterion(VLAN_VID)).vlanId();
1302 }
1303
1304 /**
Charles Chan72779502016-04-23 17:36:10 -07001305 * Gets the spine-facing port on ingress device of given multicast group.
1306 *
1307 * @param mcastIp multicast IP
1308 * @return spine-facing port on ingress device
1309 */
1310 private PortNumber ingressTransitPort(IpAddress mcastIp) {
Pier979e61a2018-03-07 11:42:50 +01001311 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Charles Chan72779502016-04-23 17:36:10 -07001312 .stream().findAny().orElse(null);
1313 if (ingressDevice != null) {
1314 NextObjective nextObj = mcastNextObjStore
1315 .get(new McastStoreKey(mcastIp, ingressDevice)).value();
1316 Set<PortNumber> ports = getPorts(nextObj.next());
1317
1318 for (PortNumber port : ports) {
1319 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001320 if (srManager.deviceConfiguration() != null &&
1321 srManager.deviceConfiguration().getPortSubnets(ingressDevice, port).isEmpty() &&
Charles Chan82f19972016-05-17 13:13:55 -07001322 !srManager.xConnectHandler.hasXConnect(new ConnectPoint(ingressDevice, port))) {
Charles Chan72779502016-04-23 17:36:10 -07001323 return port;
1324 }
1325 }
1326 }
1327 return null;
1328 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001329
1330 /**
Pier Luigi580fd8a2018-01-16 10:47:50 +01001331 * Verify if the given device has sinks
1332 * for the multicast group.
1333 *
1334 * @param deviceId device Id
1335 * @param mcastIp multicast IP
1336 * @return true if the device has sink for the group.
1337 * False otherwise.
1338 */
1339 private boolean hasSinks(DeviceId deviceId, IpAddress mcastIp) {
1340 if (deviceId != null) {
1341 // Get the nextobjective
1342 Versioned<NextObjective> versionedNextObj = mcastNextObjStore.get(
1343 new McastStoreKey(mcastIp, deviceId)
1344 );
1345 // If it exists
1346 if (versionedNextObj != null) {
1347 NextObjective nextObj = versionedNextObj.value();
1348 // Retrieves all the output ports
1349 Set<PortNumber> ports = getPorts(nextObj.next());
1350 // Tries to find at least one port that is not spine-facing
1351 for (PortNumber port : ports) {
1352 // Spine-facing port should have no subnet and no xconnect
Pier Luigi69f774d2018-02-28 12:10:50 +01001353 if (srManager.deviceConfiguration() != null &&
1354 (!srManager.deviceConfiguration().getPortSubnets(deviceId, port).isEmpty() ||
Pier Luigi580fd8a2018-01-16 10:47:50 +01001355 srManager.xConnectHandler.hasXConnect(new ConnectPoint(deviceId, port)))) {
1356 return true;
1357 }
1358 }
1359 }
1360 }
1361 return false;
1362 }
1363
1364 /**
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001365 * Removes filtering objective for given device and port.
1366 *
1367 * @param deviceId device ID
1368 * @param port ingress port number
1369 * @param assignedVlan assigned VLAN ID
1370 * @param mcastIp multicast IP address
1371 */
Pier979e61a2018-03-07 11:42:50 +01001372 private void removeFilterToDevice(DeviceId deviceId, PortNumber port,
1373 VlanId assignedVlan, IpAddress mcastIp, McastRole mcastRole) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001374 // Do nothing if the port is configured as suppressed
1375 ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
1376 SegmentRoutingAppConfig appConfig = srManager.cfgService
Pier Luigi69f774d2018-02-28 12:10:50 +01001377 .getConfig(srManager.appId(), SegmentRoutingAppConfig.class);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001378 if (appConfig != null && appConfig.suppressSubnet().contains(connectPoint)) {
1379 log.info("Ignore suppressed port {}", connectPoint);
1380 return;
1381 }
1382
Charles Chanf909e5b2018-03-02 13:26:22 -08001383 MacAddress routerMac;
1384 try {
1385 routerMac = srManager.deviceConfiguration().getDeviceMac(deviceId);
1386 } catch (DeviceConfigNotFoundException dcnfe) {
1387 log.warn("Fail to push filtering objective since device is not configured. Abort");
1388 return;
1389 }
1390
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001391 FilteringObjective.Builder filtObjBuilder =
Pier979e61a2018-03-07 11:42:50 +01001392 filterObjBuilder(port, assignedVlan, mcastIp, routerMac, mcastRole);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001393 ObjectiveContext context = new DefaultObjectiveContext(
1394 (objective) -> log.debug("Successfully removed filter on {}/{}, vlan {}",
1395 deviceId, port.toLong(), assignedVlan),
1396 (objective, error) ->
1397 log.warn("Failed to remove filter on {}/{}, vlan {}: {}",
1398 deviceId, port.toLong(), assignedVlan, error));
1399 srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.remove(context));
1400 }
1401
1402 /**
Pier Luigi35dab3f2018-01-25 16:16:02 +01001403 * Updates filtering objective for given device and port.
1404 * It is called in general when the mcast config has been
1405 * changed.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001406 *
1407 * @param deviceId device ID
1408 * @param portNum ingress port number
1409 * @param vlanId assigned VLAN ID
1410 * @param install true to add, false to remove
1411 */
Pier Luigi69f774d2018-02-28 12:10:50 +01001412 public void updateFilterToDevice(DeviceId deviceId, PortNumber portNum,
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001413 VlanId vlanId, boolean install) {
Pier Luigi35dab3f2018-01-25 16:16:02 +01001414 lastMcastChange = Instant.now();
1415 mcastLock();
1416 try {
1417 // Iterates over the route and updates properly the filtering objective
1418 // on the source device.
1419 srManager.multicastRouteService.getRoutes().forEach(mcastRoute -> {
1420 ConnectPoint source = srManager.multicastRouteService.fetchSource(mcastRoute);
1421 if (source.deviceId().equals(deviceId) && source.port().equals(portNum)) {
1422 if (install) {
Pier979e61a2018-03-07 11:42:50 +01001423 addFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), INGRESS);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001424 } else {
Pier979e61a2018-03-07 11:42:50 +01001425 removeFilterToDevice(deviceId, portNum, vlanId, mcastRoute.group(), null);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001426 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001427 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001428 });
1429 } finally {
1430 mcastUnlock();
1431 }
1432 }
1433
Pier Luigi6786b922018-02-02 16:19:11 +01001434 private boolean isLeader(ConnectPoint source) {
1435 // Continue only when we have the mastership on the operation
1436 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1437 // When the source is available we just check the mastership
1438 if (srManager.deviceService.isAvailable(source.deviceId())) {
1439 return false;
1440 }
1441 // Fallback with Leadership service
1442 // source id is used a topic
1443 NodeId leader = srManager.leadershipService.runForLeadership(
1444 source.deviceId().toString()).leaderNodeId();
1445 // Verify if this node is the leader
1446 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1447 return false;
1448 }
1449 }
1450 // Done
1451 return true;
1452 }
1453
Pier Luigi35dab3f2018-01-25 16:16:02 +01001454 /**
1455 * Performs bucket verification operation for all mcast groups in the devices.
1456 * Firstly, it verifies that mcast is stable before trying verification operation.
1457 * Verification consists in creating new nexts with VERIFY operation. Actually,
1458 * the operation is totally delegated to the driver.
1459 */
1460 private final class McastBucketCorrector implements Runnable {
1461
1462 @Override
1463 public void run() {
1464 // Verify if the Mcast has been stable for MCAST_STABLITY_THRESHOLD
1465 if (!isMcastStable()) {
1466 return;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001467 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001468 // Acquires lock
1469 mcastLock();
1470 try {
1471 // Iterates over the routes and verify the related next objectives
1472 srManager.multicastRouteService.getRoutes()
1473 .stream()
1474 .map(McastRoute::group)
1475 .forEach(mcastIp -> {
1476 log.trace("Running mcast buckets corrector for mcast group: {}",
1477 mcastIp);
1478
1479 // For each group we get current information in the store
1480 // and issue a check of the next objectives in place
Pier979e61a2018-03-07 11:42:50 +01001481 DeviceId ingressDevice = getDevice(mcastIp, INGRESS)
Pier Luigi35dab3f2018-01-25 16:16:02 +01001482 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +01001483 DeviceId transitDevice = getDevice(mcastIp, TRANSIT)
Pier Luigi35dab3f2018-01-25 16:16:02 +01001484 .stream().findAny().orElse(null);
Pier979e61a2018-03-07 11:42:50 +01001485 Set<DeviceId> egressDevices = getDevice(mcastIp, EGRESS);
Pier Luigi92e69be2018-03-02 12:53:37 +01001486 // Get source and sinks from Mcast Route Service and warn about errors
Pier Luigi35dab3f2018-01-25 16:16:02 +01001487 ConnectPoint source = getSource(mcastIp);
Pier Luigi92e69be2018-03-02 12:53:37 +01001488 Set<ConnectPoint> sinks = getSinks(mcastIp);
Pier Luigi35dab3f2018-01-25 16:16:02 +01001489
1490 // Do not proceed if ingress device or source of this group are missing
1491 if (ingressDevice == null || source == null) {
Pier Luigi92e69be2018-03-02 12:53:37 +01001492 if (!sinks.isEmpty()) {
1493 log.warn("Unable to run buckets corrector. " +
1494 "Missing ingress {} or source {} for group {}",
1495 ingressDevice, source, mcastIp);
1496 }
Pier Luigi35dab3f2018-01-25 16:16:02 +01001497 return;
1498 }
1499
1500 // Continue only when this instance is the master of source device
1501 if (!srManager.mastershipService.isLocalMaster(source.deviceId())) {
1502 log.trace("Unable to run buckets corrector. " +
1503 "Skip {} due to lack of mastership " +
1504 "of the source device {}",
1505 mcastIp, source.deviceId());
1506 return;
1507 }
1508
1509 // Create the set of the devices to be processed
1510 ImmutableSet.Builder<DeviceId> devicesBuilder = ImmutableSet.builder();
1511 devicesBuilder.add(ingressDevice);
1512 if (transitDevice != null) {
1513 devicesBuilder.add(transitDevice);
1514 }
1515 if (!egressDevices.isEmpty()) {
1516 devicesBuilder.addAll(egressDevices);
1517 }
1518 Set<DeviceId> devicesToProcess = devicesBuilder.build();
1519
1520 // Iterate over the devices
1521 devicesToProcess.forEach(deviceId -> {
1522 McastStoreKey currentKey = new McastStoreKey(mcastIp, deviceId);
1523 // If next exists in our store verify related next objective
1524 if (mcastNextObjStore.containsKey(currentKey)) {
1525 NextObjective currentNext = mcastNextObjStore.get(currentKey).value();
1526 // Get current ports
1527 Set<PortNumber> currentPorts = getPorts(currentNext.next());
1528 // Rebuild the next objective
1529 currentNext = nextObjBuilder(
1530 mcastIp,
1531 assignedVlan(deviceId.equals(source.deviceId()) ? source : null),
1532 currentPorts,
1533 currentNext.id()
1534 ).verify();
1535 // Send to the flowobjective service
1536 srManager.flowObjectiveService.next(deviceId, currentNext);
1537 } else {
Pier Luigid8a15162018-02-15 16:33:08 +01001538 log.warn("Unable to run buckets corrector. " +
Pier Luigi35dab3f2018-01-25 16:16:02 +01001539 "Missing next for {} and group {}",
1540 deviceId, mcastIp);
1541 }
1542 });
1543
1544 });
1545 } finally {
1546 // Finally, it releases the lock
1547 mcastUnlock();
1548 }
1549
1550 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001551 }
Pier Luigi0f9635b2018-01-15 18:06:43 +01001552
1553 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
1554 // If mcast ip is present
1555 if (mcastIp != null) {
1556 return mcastNextObjStore.entrySet().stream()
1557 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1558 .collect(Collectors.toMap(Map.Entry::getKey,
1559 entry -> entry.getValue().value().id()));
1560 }
1561 // Otherwise take all the groups
1562 return mcastNextObjStore.entrySet().stream()
1563 .collect(Collectors.toMap(Map.Entry::getKey,
1564 entry -> entry.getValue().value().id()));
1565 }
1566
Pier Luigi69f774d2018-02-28 12:10:50 +01001567 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +01001568 // If mcast ip is present
1569 if (mcastIp != null) {
1570 return mcastRoleStore.entrySet().stream()
1571 .filter(mcastEntry -> mcastIp.equals(mcastEntry.getKey().mcastIp()))
1572 .collect(Collectors.toMap(Map.Entry::getKey,
1573 entry -> entry.getValue().value()));
1574 }
1575 // Otherwise take all the groups
1576 return mcastRoleStore.entrySet().stream()
1577 .collect(Collectors.toMap(Map.Entry::getKey,
1578 entry -> entry.getValue().value()));
1579 }
1580
1581 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
1582 Map<ConnectPoint, List<ConnectPoint>> mcastPaths = Maps.newHashMap();
1583 // Get the source
1584 ConnectPoint source = getSource(mcastIp);
1585 // Source cannot be null, we don't know the starting point
1586 if (source != null) {
1587 // Init steps
1588 Set<DeviceId> visited = Sets.newHashSet();
1589 List<ConnectPoint> currentPath = Lists.newArrayList(
1590 source
1591 );
1592 // Build recursively the mcast paths
1593 buildMcastPaths(source.deviceId(), visited, mcastPaths, currentPath, mcastIp);
1594 }
1595 return mcastPaths;
1596 }
1597
1598 private void buildMcastPaths(DeviceId toVisit, Set<DeviceId> visited,
1599 Map<ConnectPoint, List<ConnectPoint>> mcastPaths,
1600 List<ConnectPoint> currentPath, IpAddress mcastIp) {
1601 // If we have visited the node to visit
1602 // there is a loop
1603 if (visited.contains(toVisit)) {
1604 return;
1605 }
1606 // Visit next-hop
1607 visited.add(toVisit);
1608 McastStoreKey mcastStoreKey = new McastStoreKey(mcastIp, toVisit);
1609 // Looking for next-hops
1610 if (mcastNextObjStore.containsKey(mcastStoreKey)) {
1611 // Build egress connectpoints
1612 NextObjective nextObjective = mcastNextObjStore.get(mcastStoreKey).value();
1613 // Get Ports
1614 Set<PortNumber> outputPorts = getPorts(nextObjective.next());
1615 // Build relative cps
1616 ImmutableSet.Builder<ConnectPoint> cpBuilder = ImmutableSet.builder();
1617 outputPorts.forEach(portNumber -> cpBuilder.add(new ConnectPoint(toVisit, portNumber)));
1618 Set<ConnectPoint> egressPoints = cpBuilder.build();
1619 // Define other variables for the next steps
1620 Set<Link> egressLinks;
1621 List<ConnectPoint> newCurrentPath;
1622 Set<DeviceId> newVisited;
1623 DeviceId newToVisit;
1624 for (ConnectPoint egressPoint : egressPoints) {
1625 egressLinks = srManager.linkService.getEgressLinks(egressPoint);
1626 // If it does not have egress links, stop
1627 if (egressLinks.isEmpty()) {
1628 // Add the connect points to the path
1629 newCurrentPath = Lists.newArrayList(currentPath);
1630 newCurrentPath.add(0, egressPoint);
1631 // Save in the map
1632 mcastPaths.put(egressPoint, newCurrentPath);
1633 } else {
1634 newVisited = Sets.newHashSet(visited);
1635 // Iterate over the egress links for the next hops
1636 for (Link egressLink : egressLinks) {
1637 // Update to visit
1638 newToVisit = egressLink.dst().deviceId();
1639 // Add the connect points to the path
1640 newCurrentPath = Lists.newArrayList(currentPath);
1641 newCurrentPath.add(0, egressPoint);
1642 newCurrentPath.add(0, egressLink.dst());
1643 // Go to the next hop
1644 buildMcastPaths(newToVisit, newVisited, mcastPaths, newCurrentPath, mcastIp);
1645 }
1646 }
1647 }
1648 }
1649 }
1650
Charles Chanc91c8782016-03-30 17:54:24 -07001651}