blob: f1b942967cd799e015e34c4c68508c397eda52a0 [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;
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000160 private VlanId mcastInnerVlan = VlanId.NONE;
alshabib3b1eadc2016-02-01 17:57:00 -0800161
Carmelo Cascone995fd682019-11-14 14:22:39 -0800162 /**
163 * Whether to use VLAN for multicast traffic.
164 **/
alshabib09069c92016-02-21 14:49:51 -0800165 private boolean vlanEnabled = DEFAULT_VLAN_ENABLED;
alshabibfc1cb032016-02-17 15:37:56 -0800166
Carmelo Cascone995fd682019-11-14 14:22:39 -0800167 /**
168 * Priority for multicast rules.
169 **/
alshabib3b1eadc2016-02-01 17:57:00 -0800170 private int priority = DEFAULT_PRIORITY;
171
ke hanf1709e82016-08-12 10:48:17 +0800172 private static final Class<McastConfig> CORD_MCAST_CONFIG_CLASS =
173 McastConfig.class;
174
175 private ConfigFactory<ApplicationId, McastConfig> cordMcastConfigFactory =
176 new ConfigFactory<ApplicationId, McastConfig>(
177 SubjectFactories.APP_SUBJECT_FACTORY, CORD_MCAST_CONFIG_CLASS, "multicast") {
178 @Override
179 public McastConfig createConfig() {
180 return new McastConfig();
181 }
182 };
Jonathan Hart28271642016-02-10 16:13:54 -0800183
Esin Karaman39b24852019-08-28 13:57:30 +0000184 // lock to synchronize local operations
185 private final Lock mcastLock = new ReentrantLock();
186 private void mcastLock() {
187 mcastLock.lock();
188 }
189 private void mcastUnlock() {
190 mcastLock.unlock();
191 }
192 private ExecutorService eventExecutor;
193
alshabib3b1eadc2016-02-01 17:57:00 -0800194 @Activate
Jonathan Hart435ffc42016-02-19 10:32:05 -0800195 public void activate(ComponentContext context) {
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800196 componentConfigService.registerProperties(getClass());
Jonathan Hart435ffc42016-02-19 10:32:05 -0800197 modified(context);
198
Charles Chanf867c4b2017-01-20 11:22:25 -0800199 appId = coreService.registerApplication(APP_NAME);
ke hanf1709e82016-08-12 10:48:17 +0800200 coreAppId = coreService.registerApplication(CoreService.CORE_APP_NAME);
Jonathan Hart28271642016-02-10 16:13:54 -0800201
Esin Karaman39b24852019-08-28 13:57:30 +0000202 eventExecutor = newSingleThreadScheduledExecutor(groupedThreads("cord/mcast",
203 "events-mcast-%d", log));
204
205 KryoNamespace.Builder groupsKryo = new KryoNamespace.Builder()
206 .register(KryoNamespaces.API)
207 .register(NextKey.class)
208 .register(NextContent.class);
209 groups = storageService
210 .<NextKey, NextContent>consistentMapBuilder()
211 .withName("cord-mcast-groups-store")
212 .withSerializer(Serializer.using(groupsKryo.build("CordMcast-Groups")))
213 .build();
214
ke hanf1709e82016-08-12 10:48:17 +0800215 networkConfig.registerConfigFactory(cordMcastConfigFactory);
216 networkConfig.addListener(configListener);
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800217 mcastService.addListener(listener);
218
alshabib09069c92016-02-21 14:49:51 -0800219 mcastService.getRoutes().stream()
Esin Karaman39b24852019-08-28 13:57:30 +0000220 .map(r -> new ImmutablePair<>(r, mcastService.sinks(r)))
alshabib09069c92016-02-21 14:49:51 -0800221 .filter(pair -> pair.getRight() != null && !pair.getRight().isEmpty())
Esin Karaman39b24852019-08-28 13:57:30 +0000222 .forEach(pair -> pair.getRight().forEach(sink -> addSink(pair.getLeft(),
223 sink)));
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800224
ke hanf1709e82016-08-12 10:48:17 +0800225 McastConfig config = networkConfig.getConfig(coreAppId, CORD_MCAST_CONFIG_CLASS);
Esin Karaman39b24852019-08-28 13:57:30 +0000226 updateConfig(config);
alshabib3b1eadc2016-02-01 17:57:00 -0800227 log.info("Started");
228 }
229
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000230 @Modified
231 public void modified(ComponentContext context) {
232 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
233
234 String s = get(properties, VLAN_ENABLED);
235 vlanEnabled = isNullOrEmpty(s) ? DEFAULT_VLAN_ENABLED : Boolean.parseBoolean(s.trim());
236
237 try {
238 s = get(properties, PRIORITY);
239 priority = isNullOrEmpty(s) ? DEFAULT_PRIORITY : Integer.parseInt(s.trim());
240 } catch (NumberFormatException ne) {
241 log.error("Unable to parse configuration parameter for priority", ne);
242 priority = DEFAULT_PRIORITY;
243 }
244 cordMcastStatisticsService.setVlanValue(assignedVlan());
245 }
246
alshabib3b1eadc2016-02-01 17:57:00 -0800247 @Deactivate
248 public void deactivate() {
Jonathan Hartc3f84eb2016-02-19 12:44:36 -0800249 componentConfigService.unregisterProperties(getClass(), false);
alshabib3b1eadc2016-02-01 17:57:00 -0800250 mcastService.removeListener(listener);
ke hanf1709e82016-08-12 10:48:17 +0800251 networkConfig.removeListener(configListener);
ke han9590c812017-02-28 15:02:26 +0800252 networkConfig.unregisterConfigFactory(cordMcastConfigFactory);
Esin Karaman39b24852019-08-28 13:57:30 +0000253 eventExecutor.shutdown();
ke han9590c812017-02-28 15:02:26 +0800254 clearGroups();
Esin Karaman39b24852019-08-28 13:57:30 +0000255 groups.destroy();
alshabib3b1eadc2016-02-01 17:57:00 -0800256 log.info("Stopped");
257 }
258
ke han9590c812017-02-28 15:02:26 +0800259 public void clearGroups() {
Esin Karaman39b24852019-08-28 13:57:30 +0000260 mcastLock();
261 try {
262 groups.keySet().forEach(groupInfo -> {
263 if (!isLocalLeader(groupInfo.getDevice())) {
264 return;
265 }
266 NextContent next = groups.get(groupInfo).value();
267
Sonal Kasliwala0bbe6c2020-01-06 10:46:30 +0000268 if (next != null) {
269 ObjectiveContext context = new DefaultObjectiveContext(
270 (objective) -> log.debug("Successfully remove {}",
271 groupInfo.group),
272 (objective, error) -> log.warn("Failed to remove {}: {}",
273 groupInfo.group, error));
274 // remove the flow rule
275 flowObjectiveService.forward(groupInfo.getDevice(), fwdObject(next.getNextId(),
276 groupInfo.group).remove(context));
277 // remove all ports from the group
278 next.getOutPorts().stream().forEach(portNumber ->
279 flowObjectiveService.next(groupInfo.getDevice(), nextObject(next.getNextId(),
280 portNumber,
281 NextType.RemoveFromExisting,
282 groupInfo.group))
283 );
Esin Karaman39b24852019-08-28 13:57:30 +0000284
Sonal Kasliwala0bbe6c2020-01-06 10:46:30 +0000285 }
Esin Karaman39b24852019-08-28 13:57:30 +0000286 });
287 groups.clear();
288 } finally {
289 mcastUnlock();
290 }
291 }
292
293 private VlanId multicastVlan() {
294 return VlanId.vlanId(mcastVlan);
295 }
296
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000297 protected VlanId assignedVlan() {
Esin Karaman39b24852019-08-28 13:57:30 +0000298 return vlanEnabled ? multicastVlan() : VlanId.NONE;
ke han9590c812017-02-28 15:02:26 +0800299 }
300
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000301 protected VlanId assignedInnerVlan() {
302 return vlanEnabled ? mcastInnerVlan : VlanId.NONE;
303 }
304
alshabib3b1eadc2016-02-01 17:57:00 -0800305 private class InternalMulticastListener implements McastListener {
306 @Override
307 public void event(McastEvent event) {
Esin Karaman39b24852019-08-28 13:57:30 +0000308 eventExecutor.execute(() -> {
309 switch (event.type()) {
310 case ROUTE_ADDED:
311 case ROUTE_REMOVED:
312 case SOURCES_ADDED:
313 break;
314 case SINKS_ADDED:
315 addSinks(event);
316 break;
317 case SINKS_REMOVED:
318 removeSinks(event);
319 break;
320 default:
321 log.warn("Unknown mcast event {}", event.type());
322 }
323 });
324 }
325 }
326
327 /**
328 * Processes previous, and new sinks then finds the sinks to be removed.
329 * @param prevSinks the previous sinks to be evaluated
330 * @param newSinks the new sinks to be evaluated
331 * @returnt the set of the sinks to be removed
332 */
333 private Set<ConnectPoint> getSinksToBeRemoved(Map<HostId, Set<ConnectPoint>> prevSinks,
334 Map<HostId, Set<ConnectPoint>> newSinks) {
335 return getSinksToBeProcessed(prevSinks, newSinks);
336 }
337
338
339 /**
340 * Processes previous, and new sinks then finds the sinks to be added.
341 * @param newSinks the new sinks to be processed
342 * @param allPrevSinks all previous sinks
343 * @return the set of the sinks to be added
344 */
345 private Set<ConnectPoint> getSinksToBeAdded(Map<HostId, Set<ConnectPoint>> newSinks,
346 Map<HostId, Set<ConnectPoint>> allPrevSinks) {
347 return getSinksToBeProcessed(newSinks, allPrevSinks);
348 }
349
350 /**
351 * Gets single-homed sinks that are in set1 but not in set2.
352 * @param sinkSet1 the first sink map
353 * @param sinkSet2 the second sink map
354 * @return a set containing all the single-homed sinks found in set1 but not in set2
355 */
356 private Set<ConnectPoint> getSinksToBeProcessed(Map<HostId, Set<ConnectPoint>> sinkSet1,
357 Map<HostId, Set<ConnectPoint>> sinkSet2) {
358 final Set<ConnectPoint> sinksToBeProcessed = Sets.newHashSet();
359 sinkSet1.forEach(((hostId, connectPoints) -> {
360 if (HostId.NONE.equals(hostId)) {
361 //assume all connect points associated with HostId.NONE are single homed sinks
362 sinksToBeProcessed.addAll(connectPoints);
363 return;
364 }
365 }));
366 Set<ConnectPoint> singleHomedSinksOfSet2 = sinkSet2.get(HostId.NONE) == null ?
367 Sets.newHashSet() :
368 sinkSet2.get(HostId.NONE);
369 return Sets.difference(sinksToBeProcessed, singleHomedSinksOfSet2);
370 };
371
372
373 private void removeSinks(McastEvent event) {
374 mcastLock();
375 try {
376 Set<ConnectPoint> sinksToBeRemoved = getSinksToBeRemoved(event.prevSubject().sinks(),
377 event.subject().sinks());
378 sinksToBeRemoved.forEach(sink -> removeSink(event.subject().route().group(), sink));
379 } finally {
380 mcastUnlock();
381 }
382 }
383
384 private void removeSink(IpAddress group, ConnectPoint sink) {
385 if (!isLocalLeader(sink.deviceId())) {
386 log.debug("Not the leader of {}. Skip sink_removed event for the sink {} and group {}",
387 sink.deviceId(), sink, group);
388 return;
389 }
390
Esin Karaman996177c2020-03-05 13:21:09 +0000391 Optional<SubscriberAndDeviceInformation> oltInfo = getSubscriberAndDeviceInformation(sink.deviceId());
Esin Karaman39b24852019-08-28 13:57:30 +0000392
393 if (!oltInfo.isPresent()) {
394 log.warn("Unknown OLT device : {}", sink.deviceId());
395 return;
396 }
397
398 log.debug("Removing sink {} from the group {}", sink, group);
399
400 NextKey key = new NextKey(sink.deviceId(), group);
401 groups.computeIfPresent(key, (k, v) -> {
402 flowObjectiveService.next(sink.deviceId(), nextObject(v.getNextId(), sink.port(),
403 NextType.RemoveFromExisting, group));
404
405 Set<PortNumber> outPorts = Sets.newHashSet(v.getOutPorts());
406 outPorts.remove(sink.port());
407
408 if (outPorts.isEmpty()) {
409 // this is the last sink
410 ObjectiveContext context = new DefaultObjectiveContext(
411 (objective) -> log.debug("Successfully remove {} on {}",
412 group, sink),
413 (objective, error) -> log.warn("Failed to remove {} on {}: {}",
414 group, sink, error));
415 ForwardingObjective fwdObj = fwdObject(v.getNextId(), group).remove(context);
416 flowObjectiveService.forward(sink.deviceId(), fwdObj);
417 }
418 // remove the whole entity if no out port exists in the port list
419 return outPorts.isEmpty() ? null : new NextContent(v.getNextId(),
420 ImmutableSet.copyOf(outPorts));
421 });
422 }
423
424 private void addSinks(McastEvent event) {
425 mcastLock();
426 try {
427 Set<ConnectPoint> sinksToBeAdded = getSinksToBeAdded(event.subject().sinks(),
428 event.prevSubject().sinks());
429 sinksToBeAdded.forEach(sink -> addSink(event.subject().route(), sink));
430 } finally {
431 mcastUnlock();
432 }
433 }
434
435 private void addSink(McastRoute route, ConnectPoint sink) {
Arjun E Kabf9e6e2020-03-02 10:15:21 +0000436
Esin Karaman39b24852019-08-28 13:57:30 +0000437 if (!isLocalLeader(sink.deviceId())) {
438 log.debug("Not the leader of {}. Skip sink_added event for the sink {} and group {}",
439 sink.deviceId(), sink, route.group());
440 return;
441 }
442
Esin Karaman996177c2020-03-05 13:21:09 +0000443 Optional<SubscriberAndDeviceInformation> oltInfo = getSubscriberAndDeviceInformation(sink.deviceId());
Esin Karaman39b24852019-08-28 13:57:30 +0000444
445 if (!oltInfo.isPresent()) {
446 log.warn("Unknown OLT device : {}", sink.deviceId());
447 return;
448 }
449
450 log.debug("Adding sink {} to the group {}", sink, route.group());
451
452 NextKey key = new NextKey(sink.deviceId(), route.group());
453 NextObjective newNextObj;
454
455 boolean theFirstSinkOfGroup = false;
456 if (!groups.containsKey(key)) {
457 // First time someone request this mcast group via this device
458 Integer nextId = flowObjectiveService.allocateNextId();
459 newNextObj = nextObject(nextId, sink.port(), NextType.AddNew, route.group());
460 // Store the new port
461 groups.put(key, new NextContent(nextId, ImmutableSet.of(sink.port())));
462 theFirstSinkOfGroup = true;
463 } else {
464 // This device already serves some subscribers of this mcast group
465 Versioned<NextContent> nextObj = groups.get(key);
466 if (nextObj.value().getOutPorts().contains(sink.port())) {
467 log.info("Group {} already serves the sink connected to {}", route.group(), sink);
468 return;
469 }
470 newNextObj = nextObject(nextObj.value().getNextId(), sink.port(),
471 NextType.AddToExisting, route.group());
472 // add new port to the group
473 Set<PortNumber> outPorts = Sets.newHashSet(nextObj.value().getOutPorts());
474 outPorts.add(sink.port());
475 groups.put(key, new NextContent(newNextObj.id(), ImmutableSet.copyOf(outPorts)));
476 }
477
478 ObjectiveContext context = new DefaultObjectiveContext(
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000479 (objective) -> log.debug("Successfully add {} on {}/{}, vlan {}, inner vlan {}",
Esin Karaman39b24852019-08-28 13:57:30 +0000480 route.group(), sink.deviceId(), sink.port().toLong(),
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000481 assignedVlan(), assignedInnerVlan()),
Esin Karaman39b24852019-08-28 13:57:30 +0000482 (objective, error) -> {
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000483 log.warn("Failed to add {} on {}/{}, vlan {}, inner vlan {}: {}",
Esin Karaman39b24852019-08-28 13:57:30 +0000484 route.group(), sink.deviceId(), sink.port().toLong(), assignedVlan(),
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000485 assignedInnerVlan(), error);
Esin Karaman39b24852019-08-28 13:57:30 +0000486 });
487
488 flowObjectiveService.next(sink.deviceId(), newNextObj);
489
490 if (theFirstSinkOfGroup) {
491 // create the necessary flow rule if this is the first sink request for the group
492 // on this device
493 flowObjectiveService.forward(sink.deviceId(), fwdObject(newNextObj.id(),
494 route.group()).add(context));
495 }
496 }
497
Esin Karaman996177c2020-03-05 13:21:09 +0000498 /**
499 * Fetches device information associated with the device serial number from SADIS.
500 *
501 * @param serialNumber serial number of a device
502 * @return device information; an empty Optional otherwise.
503 */
504 private Optional<SubscriberAndDeviceInformation> getSubscriberAndDeviceInformation(String serialNumber) {
505 long start = System.currentTimeMillis();
506 try {
507 return Optional.ofNullable(sadisService.getSubscriberInfoService().get(serialNumber));
508 } finally {
509 if (log.isDebugEnabled()) {
510 // SADIS may call remote systems to fetch device data and this calls can take a long time.
511 // This measurement is just for monitoring these kinds of situations.
512 log.debug("Device fetched from SADIS. Elapsed {} msec", System.currentTimeMillis() - start);
513 }
514
515 }
516 }
517
518 /**
519 * Fetches device information associated with the device serial number from SADIS.
520 *
521 * @param deviceId device id
522 * @return device information; an empty Optional otherwise.
523 */
524 private Optional<SubscriberAndDeviceInformation> getSubscriberAndDeviceInformation(DeviceId deviceId) {
525 Device device = deviceService.getDevice(deviceId);
526 if (device == null || device.serialNumber() == null) {
527 return Optional.empty();
528 }
529 return getSubscriberAndDeviceInformation(device.serialNumber());
530 }
531
Esin Karaman39b24852019-08-28 13:57:30 +0000532 private class InternalNetworkConfigListener implements NetworkConfigListener {
533 @Override
534 public void event(NetworkConfigEvent event) {
535 eventExecutor.execute(() -> {
536 switch (event.type()) {
537
538 case CONFIG_ADDED:
539 case CONFIG_UPDATED:
540 if (event.configClass().equals(CORD_MCAST_CONFIG_CLASS)) {
541 McastConfig config = networkConfig.getConfig(coreAppId, CORD_MCAST_CONFIG_CLASS);
542 if (config != null) {
543 //TODO: Simply remove flows/groups, hosts will response period query
544 // and re-sent IGMP report, so the flows can be rebuild.
545 // However, better to remove and re-add mcast flow rules here
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000546 if (vlanEnabled && (mcastVlan != config.egressVlan().toShort() ||
547 !mcastInnerVlan.equals(config.egressInnerVlan()))) {
Esin Karaman39b24852019-08-28 13:57:30 +0000548 clearGroups();
549 }
550 updateConfig(config);
551 }
552 }
553 break;
554 case CONFIG_REGISTERED:
555 case CONFIG_UNREGISTERED:
556 case CONFIG_REMOVED:
557 break;
558 default:
559 break;
560 }
561 });
562 }
563 }
564
565 private void updateConfig(McastConfig config) {
566 if (config == null) {
567 return;
568 }
569 log.debug("multicast config received: {}", config);
570
571 if (config.egressVlan() != null) {
572 mcastVlan = config.egressVlan().toShort();
573 }
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000574 if (config.egressInnerVlan() != null) {
575 mcastInnerVlan = config.egressInnerVlan();
576 }
Esin Karaman39b24852019-08-28 13:57:30 +0000577 }
578
579 private class NextKey {
580 private DeviceId device;
581 private IpAddress group;
582
583 public NextKey(DeviceId deviceId, IpAddress groupAddress) {
584 device = deviceId;
585 group = groupAddress;
586 }
587
588 public DeviceId getDevice() {
589 return device;
590 }
591
592 public int hashCode() {
593 return Objects.hash(this.device, this.group);
594 }
595
596 public boolean equals(Object obj) {
597 if (this == obj) {
598 return true;
599 } else if (!(obj instanceof NextKey)) {
600 return false;
601 } else {
602 NextKey that = (NextKey) obj;
603 return this.getClass() == that.getClass() &&
604 Objects.equals(this.device, that.device) &&
605 Objects.equals(this.group, that.group);
606 }
607 }
608 }
609
610 private class NextContent {
611 private Integer nextId;
612 private Set<PortNumber> outPorts;
613
614 public NextContent(Integer nextId, Set<PortNumber> outPorts) {
615 this.nextId = nextId;
616 this.outPorts = outPorts;
617 }
618
619 public Integer getNextId() {
620 return nextId;
621 }
622
623 public Set<PortNumber> getOutPorts() {
624 return ImmutableSet.copyOf(outPorts);
625 }
626
627 public int hashCode() {
628 return Objects.hash(this.nextId, this.outPorts);
629 }
630
631 public boolean equals(Object obj) {
632 if (this == obj) {
633 return true;
634 } else if (!(obj instanceof NextContent)) {
635 return false;
636 } else {
637 NextContent that = (NextContent) obj;
638 return this.getClass() == that.getClass() &&
639 Objects.equals(this.nextId, that.nextId) &&
640 Objects.equals(this.outPorts, that.outPorts);
alshabib3b1eadc2016-02-01 17:57:00 -0800641 }
642 }
643 }
644
ke han9590c812017-02-28 15:02:26 +0800645 private enum NextType { AddNew, AddToExisting, Remove, RemoveFromExisting };
646
Esin Karaman39b24852019-08-28 13:57:30 +0000647 private NextObjective nextObject(Integer nextId, PortNumber port,
648 NextType nextType, IpAddress mcastIp) {
ke han9590c812017-02-28 15:02:26 +0800649
Esin Karaman39b24852019-08-28 13:57:30 +0000650 // Build the meta selector with the fwd objective info
651 TrafficSelector.Builder metadata = DefaultTrafficSelector.builder()
652 .matchIPDst(mcastIp.toIpPrefix());
653
654 if (vlanEnabled) {
655 metadata.matchVlanId(multicastVlan());
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000656
657 if (!mcastInnerVlan.equals(VlanId.NONE)) {
658 metadata.matchInnerVlanId(mcastInnerVlan);
659 }
Esin Karaman39b24852019-08-28 13:57:30 +0000660 }
661
ke han9590c812017-02-28 15:02:26 +0800662 DefaultNextObjective.Builder build = DefaultNextObjective.builder()
663 .fromApp(appId)
664 .addTreatment(DefaultTrafficTreatment.builder().setOutput(port).build())
665 .withType(NextObjective.Type.BROADCAST)
Esin Karaman39b24852019-08-28 13:57:30 +0000666 .withId(nextId)
667 .withMeta(metadata.build());
668
ke han9590c812017-02-28 15:02:26 +0800669 ObjectiveContext content = new ObjectiveContext() {
670 @Override
671 public void onSuccess(Objective objective) {
Esin Karaman39b24852019-08-28 13:57:30 +0000672 log.debug("Next Objective {} installed", objective.id());
ke han9590c812017-02-28 15:02:26 +0800673 }
674
675 @Override
676 public void onError(Objective objective, ObjectiveError error) {
Esin Karaman39b24852019-08-28 13:57:30 +0000677 log.debug("Next Objective {} failed, because {}",
678 objective.id(),
679 error);
ke han9590c812017-02-28 15:02:26 +0800680 }
681 };
682
683 switch (nextType) {
684 case AddNew:
685 return build.add(content);
686 case AddToExisting:
687 return build.addToExisting(content);
688 case Remove:
689 return build.remove(content);
690 case RemoveFromExisting:
691 return build.removeFromExisting(content);
692 default:
693 return null;
694 }
695 }
696
Esin Karaman39b24852019-08-28 13:57:30 +0000697 private ForwardingObjective.Builder fwdObject(int nextId, IpAddress mcastIp) {
698 TrafficSelector.Builder mcast = DefaultTrafficSelector.builder()
699 .matchEthType(Ethernet.TYPE_IPV4)
700 .matchIPDst(mcastIp.toIpPrefix());
ke han9590c812017-02-28 15:02:26 +0800701
Esin Karaman39b24852019-08-28 13:57:30 +0000702 //build the meta selector
703 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
704 if (vlanEnabled) {
705 metabuilder.matchVlanId(multicastVlan());
Esin Karamanbb35a3b2020-03-18 13:53:24 +0000706
707 if (!mcastInnerVlan.equals(VlanId.NONE)) {
708 metabuilder.matchInnerVlanId(mcastInnerVlan);
709 }
Jonathan Hart718c0452016-02-18 15:56:22 -0800710 }
711
Esin Karaman39b24852019-08-28 13:57:30 +0000712 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective.builder()
713 .fromApp(appId)
714 .nextStep(nextId)
715 .makePermanent()
716 .withFlag(ForwardingObjective.Flag.SPECIFIC)
717 .withPriority(priority)
718 .withSelector(mcast.build())
719 .withMeta(metabuilder.build());
alshabibfc1cb032016-02-17 15:37:56 -0800720
Esin Karaman39b24852019-08-28 13:57:30 +0000721 return fwdBuilder;
alshabibfc1cb032016-02-17 15:37:56 -0800722 }
723
Esin Karaman39b24852019-08-28 13:57:30 +0000724 // Custom-built function, when the device is not available we need a fallback mechanism
725 private boolean isLocalLeader(DeviceId deviceId) {
726 if (!mastershipService.isLocalMaster(deviceId)) {
727 // When the device is available we just check the mastership
728 if (deviceService.isAvailable(deviceId)) {
ke han9590c812017-02-28 15:02:26 +0800729 return false;
ke han9590c812017-02-28 15:02:26 +0800730 }
Esin Karaman39b24852019-08-28 13:57:30 +0000731 // Fallback with Leadership service - device id is used as topic
732 NodeId leader = leadershipService.runForLeadership(
733 deviceId.toString()).leaderNodeId();
734 // Verify if this node is the leader
735 return clusterService.getLocalNode().id().equals(leader);
ke han9590c812017-02-28 15:02:26 +0800736 }
Esin Karaman39b24852019-08-28 13:57:30 +0000737 return true;
ke han9590c812017-02-28 15:02:26 +0800738 }
Esin Karaman39b24852019-08-28 13:57:30 +0000739
alshabib3b1eadc2016-02-01 17:57:00 -0800740}
ke hanf1709e82016-08-12 10:48:17 +0800741
ke han9590c812017-02-28 15:02:26 +0800742