blob: e014b790fdccf0ea2a64ea37ef892043d495cf6c [file] [log] [blame]
alshabib3b1eadc2016-02-01 17:57:00 -08001/*
Brian O'Connorcf85aa82017-08-03 22:46:01 -07002 * Copyright 2016-present Open Networking Foundation
alshabib3b1eadc2016-02-01 17:57:00 -08003 *
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 */
Daniele Moro8ea9e102020-03-24 18:56:52 +010016package org.opencord.cordmcast.impl;
alshabib3b1eadc2016-02-01 17:57:00 -080017
Esin Karaman39b24852019-08-28 13:57:30 +000018import com.google.common.collect.ImmutableSet;
19import com.google.common.collect.Sets;
alshabib09069c92016-02-21 14:49:51 -080020import org.apache.commons.lang3.tuple.ImmutablePair;
alshabib3b1eadc2016-02-01 17:57:00 -080021import org.onlab.packet.Ethernet;
alshabib3b1eadc2016-02-01 17:57:00 -080022import org.onlab.packet.IpAddress;
23import org.onlab.packet.VlanId;
Esin Karaman39b24852019-08-28 13:57:30 +000024import org.onlab.util.KryoNamespace;
Jonathan Hart28271642016-02-10 16:13:54 -080025import org.onosproject.cfg.ComponentConfigService;
Esin Karaman39b24852019-08-28 13:57:30 +000026import org.onosproject.cluster.ClusterService;
27import org.onosproject.cluster.LeadershipService;
28import org.onosproject.cluster.NodeId;
alshabib3b1eadc2016-02-01 17:57:00 -080029import org.onosproject.core.ApplicationId;
30import org.onosproject.core.CoreService;
Esin Karaman39b24852019-08-28 13:57:30 +000031import org.onosproject.mastership.MastershipService;
32import org.onosproject.mcast.api.McastEvent;
33import org.onosproject.mcast.api.McastListener;
34import org.onosproject.mcast.api.McastRoute;
35import org.onosproject.mcast.api.MulticastRouteService;
alshabib3b1eadc2016-02-01 17:57:00 -080036import org.onosproject.net.ConnectPoint;
Daniele Moro8ea9e102020-03-24 18:56:52 +010037import org.onosproject.net.Device;
ke han9590c812017-02-28 15:02:26 +080038import org.onosproject.net.DeviceId;
Esin Karaman39b24852019-08-28 13:57:30 +000039import org.onosproject.net.HostId;
ke han9590c812017-02-28 15:02:26 +080040import org.onosproject.net.PortNumber;
ke hanf1709e82016-08-12 10:48:17 +080041import org.onosproject.net.config.ConfigFactory;
42import org.onosproject.net.config.NetworkConfigEvent;
43import org.onosproject.net.config.NetworkConfigListener;
44import org.onosproject.net.config.NetworkConfigRegistry;
Esin Karaman39b24852019-08-28 13:57:30 +000045import org.onosproject.net.config.basics.McastConfig;
ke hanf1709e82016-08-12 10:48:17 +080046import org.onosproject.net.config.basics.SubjectFactories;
Esin Karaman39b24852019-08-28 13:57:30 +000047import org.onosproject.net.device.DeviceService;
alshabib3b1eadc2016-02-01 17:57:00 -080048import org.onosproject.net.flow.DefaultTrafficSelector;
49import org.onosproject.net.flow.DefaultTrafficTreatment;
50import org.onosproject.net.flow.TrafficSelector;
51import org.onosproject.net.flowobjective.DefaultForwardingObjective;
52import org.onosproject.net.flowobjective.DefaultNextObjective;
Esin Karaman39b24852019-08-28 13:57:30 +000053import org.onosproject.net.flowobjective.DefaultObjectiveContext;
alshabib3b1eadc2016-02-01 17:57:00 -080054import org.onosproject.net.flowobjective.FlowObjectiveService;
55import org.onosproject.net.flowobjective.ForwardingObjective;
56import org.onosproject.net.flowobjective.NextObjective;
57import org.onosproject.net.flowobjective.Objective;
58import org.onosproject.net.flowobjective.ObjectiveContext;
59import org.onosproject.net.flowobjective.ObjectiveError;
Esin Karaman39b24852019-08-28 13:57:30 +000060import org.onosproject.store.serializers.KryoNamespaces;
61import org.onosproject.store.service.ConsistentMap;
62import org.onosproject.store.service.Serializer;
63import org.onosproject.store.service.StorageService;
64import org.onosproject.store.service.Versioned;
Daniele Moro8ea9e102020-03-24 18:56:52 +010065import org.opencord.cordmcast.CordMcastService;
66import org.opencord.cordmcast.CordMcastStatisticsService;
67import org.opencord.sadis.SadisService;
68import org.opencord.sadis.SubscriberAndDeviceInformation;
Jonathan Hart28271642016-02-10 16:13:54 -080069import org.osgi.service.component.ComponentContext;
Daniele Moro8ea9e102020-03-24 18:56:52 +010070import org.osgi.service.component.annotations.Activate;
71import org.osgi.service.component.annotations.Component;
72import org.osgi.service.component.annotations.Deactivate;
73import org.osgi.service.component.annotations.Modified;
74import org.osgi.service.component.annotations.Reference;
75import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib3b1eadc2016-02-01 17:57:00 -080076import org.slf4j.Logger;
77
Jonathan Hart28271642016-02-10 16:13:54 -080078import java.util.Dictionary;
alshabib3b1eadc2016-02-01 17:57:00 -080079import java.util.Map;
ke han9590c812017-02-28 15:02:26 +080080import java.util.Objects;
Jonathan Hart0c194962016-05-23 17:08:15 -070081import java.util.Optional;
alshabibfc1cb032016-02-17 15:37:56 -080082import java.util.Properties;
Esin Karaman39b24852019-08-28 13:57:30 +000083import java.util.Set;
84import java.util.concurrent.ExecutorService;
85import java.util.concurrent.locks.Lock;
86import java.util.concurrent.locks.ReentrantLock;
alshabib3b1eadc2016-02-01 17:57:00 -080087
alshabibfc1cb032016-02-17 15:37:56 -080088import static com.google.common.base.Strings.isNullOrEmpty;
Esin Karaman39b24852019-08-28 13:57:30 +000089import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
alshabibfc1cb032016-02-17 15:37:56 -080090import static org.onlab.util.Tools.get;
Esin Karaman39b24852019-08-28 13:57:30 +000091import static org.onlab.util.Tools.groupedThreads;
Daniele Moro8ea9e102020-03-24 18:56:52 +010092import static org.opencord.cordmcast.impl.OsgiPropertyConstants.*;
alshabib3b1eadc2016-02-01 17:57:00 -080093import static org.slf4j.LoggerFactory.getLogger;
94
Esin Karaman39b24852019-08-28 13:57:30 +000095
alshabib3b1eadc2016-02-01 17:57:00 -080096/**
Jonathan Hartc3f84eb2016-02-19 12:44:36 -080097 * CORD multicast provisioning application. Operates by listening to
Jonathan Hart28271642016-02-10 16:13:54 -080098 * events on the multicast rib and provisioning groups to program multicast
alshabib3b1eadc2016-02-01 17:57:00 -080099 * flows on the dataplane.
100 */
Carmelo Cascone995fd682019-11-14 14:22:39 -0800101@Component(immediate = true,
102 property = {
103 VLAN_ENABLED + ":Boolean=" + DEFAULT_VLAN_ENABLED,
104 PRIORITY + ":Integer=" + DEFAULT_PRIORITY,
105})
Daniele Moro8ea9e102020-03-24 18:56:52 +0100106public class CordMcast implements CordMcastService {
107 private static final String APP_NAME = "org.opencord.mcast";
alshabib3b1eadc2016-02-01 17:57:00 -0800108
Jonathan Hart0c194962016-05-23 17:08:15 -0700109 private final Logger log = getLogger(getClass());
alshabib09069c92016-02-21 14:49:51 -0800110
alshabib09069c92016-02-21 14:49:51 -0800111 private static final int DEFAULT_PRIORITY = 500;
alshabib3b1eadc2016-02-01 17:57:00 -0800112 private static final short DEFAULT_MCAST_VLAN = 4000;
alshabibfc1cb032016-02-17 15:37:56 -0800113
Carmelo Cascone995fd682019-11-14 14:22:39 -0800114 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib3b1eadc2016-02-01 17:57:00 -0800115 protected MulticastRouteService mcastService;
116
Carmelo Cascone995fd682019-11-14 14:22:39 -0800117 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib3b1eadc2016-02-01 17:57:00 -0800118 protected FlowObjectiveService flowObjectiveService;
119
Carmelo Cascone995fd682019-11-14 14:22:39 -0800120 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib3b1eadc2016-02-01 17:57:00 -0800121 protected CoreService coreService;
122
Carmelo Cascone995fd682019-11-14 14:22:39 -0800123 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonathan Hart28271642016-02-10 16:13:54 -0800124 protected ComponentConfigService componentConfigService;
125
Carmelo Cascone995fd682019-11-14 14:22:39 -0800126 @Reference(cardinality = ReferenceCardinality.MANDATORY)
ke hanf1709e82016-08-12 10:48:17 +0800127 protected NetworkConfigRegistry networkConfig;
128
Carmelo Cascone995fd682019-11-14 14:22:39 -0800129 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Esin Karaman39b24852019-08-28 13:57:30 +0000130 protected StorageService storageService;
131
Carmelo Cascone995fd682019-11-14 14:22:39 -0800132 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Esin Karaman39b24852019-08-28 13:57:30 +0000133 protected MastershipService mastershipService;
134
Carmelo Cascone995fd682019-11-14 14:22:39 -0800135 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Esin Karaman39b24852019-08-28 13:57:30 +0000136 public DeviceService deviceService;
137
Carmelo Cascone995fd682019-11-14 14:22:39 -0800138 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Esin Karaman39b24852019-08-28 13:57:30 +0000139 private ClusterService clusterService;
140
Carmelo Cascone995fd682019-11-14 14:22:39 -0800141 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Esin Karaman39b24852019-08-28 13:57:30 +0000142 private LeadershipService leadershipService;
143
Esin Karaman996177c2020-03-05 13:21:09 +0000144 @Reference(cardinality = ReferenceCardinality.MANDATORY)
145 protected SadisService sadisService;
146
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000147 @Reference(cardinality = ReferenceCardinality.MANDATORY)
148 protected CordMcastStatisticsService cordMcastStatisticsService;
149
alshabib3b1eadc2016-02-01 17:57:00 -0800150 protected McastListener listener = new InternalMulticastListener();
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000151
ke hanf1709e82016-08-12 10:48:17 +0800152 private InternalNetworkConfigListener configListener =
153 new InternalNetworkConfigListener();
alshabib3b1eadc2016-02-01 17:57:00 -0800154
Esin Karaman39b24852019-08-28 13:57:30 +0000155 private ConsistentMap<NextKey, NextContent> groups;
alshabib3b1eadc2016-02-01 17:57:00 -0800156
alshabib3b1eadc2016-02-01 17:57:00 -0800157 private ApplicationId appId;
ke hanf1709e82016-08-12 10:48:17 +0800158 private ApplicationId coreAppId;
Esin Karaman39b24852019-08-28 13:57:30 +0000159 private short mcastVlan = DEFAULT_MCAST_VLAN;
alshabib3b1eadc2016-02-01 17:57:00 -0800160
Carmelo Cascone995fd682019-11-14 14:22:39 -0800161 /**
162 * Whether to use VLAN for multicast traffic.
163 **/
alshabib09069c92016-02-21 14:49:51 -0800164 private boolean vlanEnabled = DEFAULT_VLAN_ENABLED;
alshabibfc1cb032016-02-17 15:37:56 -0800165
Carmelo Cascone995fd682019-11-14 14:22:39 -0800166 /**
167 * Priority for multicast rules.
168 **/
alshabib3b1eadc2016-02-01 17:57:00 -0800169 private int priority = DEFAULT_PRIORITY;
170
ke hanf1709e82016-08-12 10:48:17 +0800171 private static final Class<McastConfig> CORD_MCAST_CONFIG_CLASS =
172 McastConfig.class;
173
174 private ConfigFactory<ApplicationId, McastConfig> cordMcastConfigFactory =
175 new ConfigFactory<ApplicationId, McastConfig>(
176 SubjectFactories.APP_SUBJECT_FACTORY, CORD_MCAST_CONFIG_CLASS, "multicast") {
177 @Override
178 public McastConfig createConfig() {
179 return new McastConfig();
180 }
181 };
Jonathan Hart28271642016-02-10 16:13:54 -0800182
Esin Karaman39b24852019-08-28 13:57:30 +0000183 // lock to synchronize local operations
184 private final Lock mcastLock = new ReentrantLock();
185 private void mcastLock() {
186 mcastLock.lock();
187 }
188 private void mcastUnlock() {
189 mcastLock.unlock();
190 }
191 private ExecutorService eventExecutor;
192
alshabib3b1eadc2016-02-01 17:57:00 -0800193 @Activate
Jonathan Hart435ffc42016-02-19 10:32:05 -0800194 public void activate(ComponentContext context) {
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800195 componentConfigService.registerProperties(getClass());
Jonathan Hart435ffc42016-02-19 10:32:05 -0800196 modified(context);
197
Charles Chanf867c4b2017-01-20 11:22:25 -0800198 appId = coreService.registerApplication(APP_NAME);
ke hanf1709e82016-08-12 10:48:17 +0800199 coreAppId = coreService.registerApplication(CoreService.CORE_APP_NAME);
Jonathan Hart28271642016-02-10 16:13:54 -0800200
Esin Karaman39b24852019-08-28 13:57:30 +0000201 eventExecutor = newSingleThreadScheduledExecutor(groupedThreads("cord/mcast",
202 "events-mcast-%d", log));
203
204 KryoNamespace.Builder groupsKryo = new KryoNamespace.Builder()
205 .register(KryoNamespaces.API)
206 .register(NextKey.class)
207 .register(NextContent.class);
208 groups = storageService
209 .<NextKey, NextContent>consistentMapBuilder()
210 .withName("cord-mcast-groups-store")
211 .withSerializer(Serializer.using(groupsKryo.build("CordMcast-Groups")))
212 .build();
213
ke hanf1709e82016-08-12 10:48:17 +0800214 networkConfig.registerConfigFactory(cordMcastConfigFactory);
215 networkConfig.addListener(configListener);
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800216 mcastService.addListener(listener);
217
alshabib09069c92016-02-21 14:49:51 -0800218 mcastService.getRoutes().stream()
Esin Karaman39b24852019-08-28 13:57:30 +0000219 .map(r -> new ImmutablePair<>(r, mcastService.sinks(r)))
alshabib09069c92016-02-21 14:49:51 -0800220 .filter(pair -> pair.getRight() != null && !pair.getRight().isEmpty())
Esin Karaman39b24852019-08-28 13:57:30 +0000221 .forEach(pair -> pair.getRight().forEach(sink -> addSink(pair.getLeft(),
222 sink)));
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800223
ke hanf1709e82016-08-12 10:48:17 +0800224 McastConfig config = networkConfig.getConfig(coreAppId, CORD_MCAST_CONFIG_CLASS);
Esin Karaman39b24852019-08-28 13:57:30 +0000225 updateConfig(config);
alshabib3b1eadc2016-02-01 17:57:00 -0800226 log.info("Started");
227 }
228
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000229 @Modified
230 public void modified(ComponentContext context) {
231 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
232
233 String s = get(properties, VLAN_ENABLED);
234 vlanEnabled = isNullOrEmpty(s) ? DEFAULT_VLAN_ENABLED : Boolean.parseBoolean(s.trim());
235
236 try {
237 s = get(properties, PRIORITY);
238 priority = isNullOrEmpty(s) ? DEFAULT_PRIORITY : Integer.parseInt(s.trim());
239 } catch (NumberFormatException ne) {
240 log.error("Unable to parse configuration parameter for priority", ne);
241 priority = DEFAULT_PRIORITY;
242 }
243 cordMcastStatisticsService.setVlanValue(assignedVlan());
244 }
245
alshabib3b1eadc2016-02-01 17:57:00 -0800246 @Deactivate
247 public void deactivate() {
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800248 componentConfigService.unregisterProperties(getClass(), false);
alshabib3b1eadc2016-02-01 17:57:00 -0800249 mcastService.removeListener(listener);
ke hanf1709e82016-08-12 10:48:17 +0800250 networkConfig.removeListener(configListener);
ke han9590c812017-02-28 15:02:26 +0800251 networkConfig.unregisterConfigFactory(cordMcastConfigFactory);
Esin Karaman39b24852019-08-28 13:57:30 +0000252 eventExecutor.shutdown();
ke han9590c812017-02-28 15:02:26 +0800253 clearGroups();
Esin Karaman39b24852019-08-28 13:57:30 +0000254 groups.destroy();
alshabib3b1eadc2016-02-01 17:57:00 -0800255 log.info("Stopped");
256 }
257
ke han9590c812017-02-28 15:02:26 +0800258 public void clearGroups() {
Esin Karaman39b24852019-08-28 13:57:30 +0000259 mcastLock();
260 try {
261 groups.keySet().forEach(groupInfo -> {
262 if (!isLocalLeader(groupInfo.getDevice())) {
263 return;
264 }
265 NextContent next = groups.get(groupInfo).value();
266
Sonal Kasliwala0bbe6c2020-01-06 10:46:30 +0000267 if (next != null) {
268 ObjectiveContext context = new DefaultObjectiveContext(
269 (objective) -> log.debug("Successfully remove {}",
270 groupInfo.group),
271 (objective, error) -> log.warn("Failed to remove {}: {}",
272 groupInfo.group, error));
273 // remove the flow rule
274 flowObjectiveService.forward(groupInfo.getDevice(), fwdObject(next.getNextId(),
275 groupInfo.group).remove(context));
276 // remove all ports from the group
277 next.getOutPorts().stream().forEach(portNumber ->
278 flowObjectiveService.next(groupInfo.getDevice(), nextObject(next.getNextId(),
279 portNumber,
280 NextType.RemoveFromExisting,
281 groupInfo.group))
282 );
Esin Karaman39b24852019-08-28 13:57:30 +0000283
Sonal Kasliwala0bbe6c2020-01-06 10:46:30 +0000284 }
Esin Karaman39b24852019-08-28 13:57:30 +0000285 });
286 groups.clear();
287 } finally {
288 mcastUnlock();
289 }
290 }
291
292 private VlanId multicastVlan() {
293 return VlanId.vlanId(mcastVlan);
294 }
295
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000296 protected VlanId assignedVlan() {
Esin Karaman39b24852019-08-28 13:57:30 +0000297 return vlanEnabled ? multicastVlan() : VlanId.NONE;
ke han9590c812017-02-28 15:02:26 +0800298 }
299
alshabib3b1eadc2016-02-01 17:57:00 -0800300 private class InternalMulticastListener implements McastListener {
301 @Override
302 public void event(McastEvent event) {
Esin Karaman39b24852019-08-28 13:57:30 +0000303 eventExecutor.execute(() -> {
304 switch (event.type()) {
305 case ROUTE_ADDED:
306 case ROUTE_REMOVED:
307 case SOURCES_ADDED:
308 break;
309 case SINKS_ADDED:
310 addSinks(event);
311 break;
312 case SINKS_REMOVED:
313 removeSinks(event);
314 break;
315 default:
316 log.warn("Unknown mcast event {}", event.type());
317 }
318 });
319 }
320 }
321
322 /**
323 * Processes previous, and new sinks then finds the sinks to be removed.
324 * @param prevSinks the previous sinks to be evaluated
325 * @param newSinks the new sinks to be evaluated
326 * @returnt the set of the sinks to be removed
327 */
328 private Set<ConnectPoint> getSinksToBeRemoved(Map<HostId, Set<ConnectPoint>> prevSinks,
329 Map<HostId, Set<ConnectPoint>> newSinks) {
330 return getSinksToBeProcessed(prevSinks, newSinks);
331 }
332
333
334 /**
335 * Processes previous, and new sinks then finds the sinks to be added.
336 * @param newSinks the new sinks to be processed
337 * @param allPrevSinks all previous sinks
338 * @return the set of the sinks to be added
339 */
340 private Set<ConnectPoint> getSinksToBeAdded(Map<HostId, Set<ConnectPoint>> newSinks,
341 Map<HostId, Set<ConnectPoint>> allPrevSinks) {
342 return getSinksToBeProcessed(newSinks, allPrevSinks);
343 }
344
345 /**
346 * Gets single-homed sinks that are in set1 but not in set2.
347 * @param sinkSet1 the first sink map
348 * @param sinkSet2 the second sink map
349 * @return a set containing all the single-homed sinks found in set1 but not in set2
350 */
351 private Set<ConnectPoint> getSinksToBeProcessed(Map<HostId, Set<ConnectPoint>> sinkSet1,
352 Map<HostId, Set<ConnectPoint>> sinkSet2) {
353 final Set<ConnectPoint> sinksToBeProcessed = Sets.newHashSet();
354 sinkSet1.forEach(((hostId, connectPoints) -> {
355 if (HostId.NONE.equals(hostId)) {
356 //assume all connect points associated with HostId.NONE are single homed sinks
357 sinksToBeProcessed.addAll(connectPoints);
358 return;
359 }
360 }));
361 Set<ConnectPoint> singleHomedSinksOfSet2 = sinkSet2.get(HostId.NONE) == null ?
362 Sets.newHashSet() :
363 sinkSet2.get(HostId.NONE);
364 return Sets.difference(sinksToBeProcessed, singleHomedSinksOfSet2);
365 };
366
367
368 private void removeSinks(McastEvent event) {
369 mcastLock();
370 try {
371 Set<ConnectPoint> sinksToBeRemoved = getSinksToBeRemoved(event.prevSubject().sinks(),
372 event.subject().sinks());
373 sinksToBeRemoved.forEach(sink -> removeSink(event.subject().route().group(), sink));
374 } finally {
375 mcastUnlock();
376 }
377 }
378
379 private void removeSink(IpAddress group, ConnectPoint sink) {
380 if (!isLocalLeader(sink.deviceId())) {
381 log.debug("Not the leader of {}. Skip sink_removed event for the sink {} and group {}",
382 sink.deviceId(), sink, group);
383 return;
384 }
385
Esin Karaman996177c2020-03-05 13:21:09 +0000386 Optional<SubscriberAndDeviceInformation> oltInfo = getSubscriberAndDeviceInformation(sink.deviceId());
Esin Karaman39b24852019-08-28 13:57:30 +0000387
388 if (!oltInfo.isPresent()) {
389 log.warn("Unknown OLT device : {}", sink.deviceId());
390 return;
391 }
392
393 log.debug("Removing sink {} from the group {}", sink, group);
394
395 NextKey key = new NextKey(sink.deviceId(), group);
396 groups.computeIfPresent(key, (k, v) -> {
397 flowObjectiveService.next(sink.deviceId(), nextObject(v.getNextId(), sink.port(),
398 NextType.RemoveFromExisting, group));
399
400 Set<PortNumber> outPorts = Sets.newHashSet(v.getOutPorts());
401 outPorts.remove(sink.port());
402
403 if (outPorts.isEmpty()) {
404 // this is the last sink
405 ObjectiveContext context = new DefaultObjectiveContext(
406 (objective) -> log.debug("Successfully remove {} on {}",
407 group, sink),
408 (objective, error) -> log.warn("Failed to remove {} on {}: {}",
409 group, sink, error));
410 ForwardingObjective fwdObj = fwdObject(v.getNextId(), group).remove(context);
411 flowObjectiveService.forward(sink.deviceId(), fwdObj);
412 }
413 // remove the whole entity if no out port exists in the port list
414 return outPorts.isEmpty() ? null : new NextContent(v.getNextId(),
415 ImmutableSet.copyOf(outPorts));
416 });
417 }
418
419 private void addSinks(McastEvent event) {
420 mcastLock();
421 try {
422 Set<ConnectPoint> sinksToBeAdded = getSinksToBeAdded(event.subject().sinks(),
423 event.prevSubject().sinks());
424 sinksToBeAdded.forEach(sink -> addSink(event.subject().route(), sink));
425 } finally {
426 mcastUnlock();
427 }
428 }
429
430 private void addSink(McastRoute route, ConnectPoint sink) {
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000431
Esin Karaman39b24852019-08-28 13:57:30 +0000432 if (!isLocalLeader(sink.deviceId())) {
433 log.debug("Not the leader of {}. Skip sink_added event for the sink {} and group {}",
434 sink.deviceId(), sink, route.group());
435 return;
436 }
437
Esin Karaman996177c2020-03-05 13:21:09 +0000438 Optional<SubscriberAndDeviceInformation> oltInfo = getSubscriberAndDeviceInformation(sink.deviceId());
Esin Karaman39b24852019-08-28 13:57:30 +0000439
440 if (!oltInfo.isPresent()) {
441 log.warn("Unknown OLT device : {}", sink.deviceId());
442 return;
443 }
444
445 log.debug("Adding sink {} to the group {}", sink, route.group());
446
447 NextKey key = new NextKey(sink.deviceId(), route.group());
448 NextObjective newNextObj;
449
450 boolean theFirstSinkOfGroup = false;
451 if (!groups.containsKey(key)) {
452 // First time someone request this mcast group via this device
453 Integer nextId = flowObjectiveService.allocateNextId();
454 newNextObj = nextObject(nextId, sink.port(), NextType.AddNew, route.group());
455 // Store the new port
456 groups.put(key, new NextContent(nextId, ImmutableSet.of(sink.port())));
457 theFirstSinkOfGroup = true;
458 } else {
459 // This device already serves some subscribers of this mcast group
460 Versioned<NextContent> nextObj = groups.get(key);
461 if (nextObj.value().getOutPorts().contains(sink.port())) {
462 log.info("Group {} already serves the sink connected to {}", route.group(), sink);
463 return;
464 }
465 newNextObj = nextObject(nextObj.value().getNextId(), sink.port(),
466 NextType.AddToExisting, route.group());
467 // add new port to the group
468 Set<PortNumber> outPorts = Sets.newHashSet(nextObj.value().getOutPorts());
469 outPorts.add(sink.port());
470 groups.put(key, new NextContent(newNextObj.id(), ImmutableSet.copyOf(outPorts)));
471 }
472
473 ObjectiveContext context = new DefaultObjectiveContext(
474 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}",
475 route.group(), sink.deviceId(), sink.port().toLong(),
476 assignedVlan()),
477 (objective, error) -> {
478 log.warn("Failed to add {} on {}/{}, vlan {}: {}",
479 route.group(), sink.deviceId(), sink.port().toLong(), assignedVlan(),
480 error);
481 });
482
483 flowObjectiveService.next(sink.deviceId(), newNextObj);
484
485 if (theFirstSinkOfGroup) {
486 // create the necessary flow rule if this is the first sink request for the group
487 // on this device
488 flowObjectiveService.forward(sink.deviceId(), fwdObject(newNextObj.id(),
489 route.group()).add(context));
490 }
491 }
492
Esin Karaman996177c2020-03-05 13:21:09 +0000493 /**
494 * Fetches device information associated with the device serial number from SADIS.
495 *
496 * @param serialNumber serial number of a device
497 * @return device information; an empty Optional otherwise.
498 */
499 private Optional<SubscriberAndDeviceInformation> getSubscriberAndDeviceInformation(String serialNumber) {
500 long start = System.currentTimeMillis();
501 try {
502 return Optional.ofNullable(sadisService.getSubscriberInfoService().get(serialNumber));
503 } finally {
504 if (log.isDebugEnabled()) {
505 // SADIS may call remote systems to fetch device data and this calls can take a long time.
506 // This measurement is just for monitoring these kinds of situations.
507 log.debug("Device fetched from SADIS. Elapsed {} msec", System.currentTimeMillis() - start);
508 }
509
510 }
511 }
512
513 /**
514 * Fetches device information associated with the device serial number from SADIS.
515 *
516 * @param deviceId device id
517 * @return device information; an empty Optional otherwise.
518 */
519 private Optional<SubscriberAndDeviceInformation> getSubscriberAndDeviceInformation(DeviceId deviceId) {
520 Device device = deviceService.getDevice(deviceId);
521 if (device == null || device.serialNumber() == null) {
522 return Optional.empty();
523 }
524 return getSubscriberAndDeviceInformation(device.serialNumber());
525 }
526
Esin Karaman39b24852019-08-28 13:57:30 +0000527 private class InternalNetworkConfigListener implements NetworkConfigListener {
528 @Override
529 public void event(NetworkConfigEvent event) {
530 eventExecutor.execute(() -> {
531 switch (event.type()) {
532
533 case CONFIG_ADDED:
534 case CONFIG_UPDATED:
535 if (event.configClass().equals(CORD_MCAST_CONFIG_CLASS)) {
536 McastConfig config = networkConfig.getConfig(coreAppId, CORD_MCAST_CONFIG_CLASS);
537 if (config != null) {
538 //TODO: Simply remove flows/groups, hosts will response period query
539 // and re-sent IGMP report, so the flows can be rebuild.
540 // However, better to remove and re-add mcast flow rules here
541 if (mcastVlan != config.egressVlan().toShort() && vlanEnabled) {
542 clearGroups();
543 }
544 updateConfig(config);
545 }
546 }
547 break;
548 case CONFIG_REGISTERED:
549 case CONFIG_UNREGISTERED:
550 case CONFIG_REMOVED:
551 break;
552 default:
553 break;
554 }
555 });
556 }
557 }
558
559 private void updateConfig(McastConfig config) {
560 if (config == null) {
561 return;
562 }
563 log.debug("multicast config received: {}", config);
564
565 if (config.egressVlan() != null) {
566 mcastVlan = config.egressVlan().toShort();
567 }
568 }
569
570 private class NextKey {
571 private DeviceId device;
572 private IpAddress group;
573
574 public NextKey(DeviceId deviceId, IpAddress groupAddress) {
575 device = deviceId;
576 group = groupAddress;
577 }
578
579 public DeviceId getDevice() {
580 return device;
581 }
582
583 public int hashCode() {
584 return Objects.hash(this.device, this.group);
585 }
586
587 public boolean equals(Object obj) {
588 if (this == obj) {
589 return true;
590 } else if (!(obj instanceof NextKey)) {
591 return false;
592 } else {
593 NextKey that = (NextKey) obj;
594 return this.getClass() == that.getClass() &&
595 Objects.equals(this.device, that.device) &&
596 Objects.equals(this.group, that.group);
597 }
598 }
599 }
600
601 private class NextContent {
602 private Integer nextId;
603 private Set<PortNumber> outPorts;
604
605 public NextContent(Integer nextId, Set<PortNumber> outPorts) {
606 this.nextId = nextId;
607 this.outPorts = outPorts;
608 }
609
610 public Integer getNextId() {
611 return nextId;
612 }
613
614 public Set<PortNumber> getOutPorts() {
615 return ImmutableSet.copyOf(outPorts);
616 }
617
618 public int hashCode() {
619 return Objects.hash(this.nextId, this.outPorts);
620 }
621
622 public boolean equals(Object obj) {
623 if (this == obj) {
624 return true;
625 } else if (!(obj instanceof NextContent)) {
626 return false;
627 } else {
628 NextContent that = (NextContent) obj;
629 return this.getClass() == that.getClass() &&
630 Objects.equals(this.nextId, that.nextId) &&
631 Objects.equals(this.outPorts, that.outPorts);
alshabib3b1eadc2016-02-01 17:57:00 -0800632 }
633 }
634 }
635
ke han9590c812017-02-28 15:02:26 +0800636 private enum NextType { AddNew, AddToExisting, Remove, RemoveFromExisting };
637
Esin Karaman39b24852019-08-28 13:57:30 +0000638 private NextObjective nextObject(Integer nextId, PortNumber port,
639 NextType nextType, IpAddress mcastIp) {
ke han9590c812017-02-28 15:02:26 +0800640
Esin Karaman39b24852019-08-28 13:57:30 +0000641 // Build the meta selector with the fwd objective info
642 TrafficSelector.Builder metadata = DefaultTrafficSelector.builder()
643 .matchIPDst(mcastIp.toIpPrefix());
644
645 if (vlanEnabled) {
646 metadata.matchVlanId(multicastVlan());
647 }
648
ke han9590c812017-02-28 15:02:26 +0800649 DefaultNextObjective.Builder build = DefaultNextObjective.builder()
650 .fromApp(appId)
651 .addTreatment(DefaultTrafficTreatment.builder().setOutput(port).build())
652 .withType(NextObjective.Type.BROADCAST)
Esin Karaman39b24852019-08-28 13:57:30 +0000653 .withId(nextId)
654 .withMeta(metadata.build());
655
ke han9590c812017-02-28 15:02:26 +0800656 ObjectiveContext content = new ObjectiveContext() {
657 @Override
658 public void onSuccess(Objective objective) {
Esin Karaman39b24852019-08-28 13:57:30 +0000659 log.debug("Next Objective {} installed", objective.id());
ke han9590c812017-02-28 15:02:26 +0800660 }
661
662 @Override
663 public void onError(Objective objective, ObjectiveError error) {
Esin Karaman39b24852019-08-28 13:57:30 +0000664 log.debug("Next Objective {} failed, because {}",
665 objective.id(),
666 error);
ke han9590c812017-02-28 15:02:26 +0800667 }
668 };
669
670 switch (nextType) {
671 case AddNew:
672 return build.add(content);
673 case AddToExisting:
674 return build.addToExisting(content);
675 case Remove:
676 return build.remove(content);
677 case RemoveFromExisting:
678 return build.removeFromExisting(content);
679 default:
680 return null;
681 }
682 }
683
Esin Karaman39b24852019-08-28 13:57:30 +0000684 private ForwardingObjective.Builder fwdObject(int nextId, IpAddress mcastIp) {
685 TrafficSelector.Builder mcast = DefaultTrafficSelector.builder()
686 .matchEthType(Ethernet.TYPE_IPV4)
687 .matchIPDst(mcastIp.toIpPrefix());
ke han9590c812017-02-28 15:02:26 +0800688
Esin Karaman39b24852019-08-28 13:57:30 +0000689 //build the meta selector
690 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
691 if (vlanEnabled) {
692 metabuilder.matchVlanId(multicastVlan());
Jonathan Hart718c0452016-02-18 15:56:22 -0800693 }
694
Esin Karaman39b24852019-08-28 13:57:30 +0000695 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder()
696 .fromApp(appId)
697 .nextStep(nextId)
698 .makePermanent()
699 .withFlag(ForwardingObjective.Flag.SPECIFIC)
700 .withPriority(priority)
701 .withSelector(mcast.build())
702 .withMeta(metabuilder.build());
alshabibfc1cb032016-02-17 15:37:56 -0800703
Esin Karaman39b24852019-08-28 13:57:30 +0000704 return fwdBuilder;
alshabibfc1cb032016-02-17 15:37:56 -0800705 }
706
Esin Karaman39b24852019-08-28 13:57:30 +0000707 // Custom-built function, when the device is not available we need a fallback mechanism
708 private boolean isLocalLeader(DeviceId deviceId) {
709 if (!mastershipService.isLocalMaster(deviceId)) {
710 // When the device is available we just check the mastership
711 if (deviceService.isAvailable(deviceId)) {
ke han9590c812017-02-28 15:02:26 +0800712 return false;
ke han9590c812017-02-28 15:02:26 +0800713 }
Esin Karaman39b24852019-08-28 13:57:30 +0000714 // Fallback with Leadership service - device id is used as topic
715 NodeId leader = leadershipService.runForLeadership(
716 deviceId.toString()).leaderNodeId();
717 // Verify if this node is the leader
718 return clusterService.getLocalNode().id().equals(leader);
ke han9590c812017-02-28 15:02:26 +0800719 }
Esin Karaman39b24852019-08-28 13:57:30 +0000720 return true;
ke han9590c812017-02-28 15:02:26 +0800721 }
Esin Karaman39b24852019-08-28 13:57:30 +0000722
alshabib3b1eadc2016-02-01 17:57:00 -0800723}
ke hanf1709e82016-08-12 10:48:17 +0800724
ke han9590c812017-02-28 15:02:26 +0800725