blob: 9947bb8581694cd1d5a379562da7a9227f328ed1 [file] [log] [blame]
Charles Chan4e87b3e2018-06-19 20:31:57 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
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 */
16package org.onosproject.segmentrouting.xconnect.impl;
17
pier6c48dba2018-11-27 11:23:50 -080018import com.google.common.collect.ImmutableList;
Charles Chan1fa010c2018-08-19 19:21:46 -070019import com.google.common.collect.ImmutableMap;
Charles Chan4e87b3e2018-06-19 20:31:57 -070020import com.google.common.collect.ImmutableSet;
pier6c48dba2018-11-27 11:23:50 -080021import com.google.common.collect.Lists;
Charles Chan4e87b3e2018-06-19 20:31:57 -070022import com.google.common.collect.Sets;
23import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
jayakumarthazhath46945b62018-10-01 00:51:54 +053029import org.onlab.packet.Ethernet;
Charles Chan4e87b3e2018-06-19 20:31:57 -070030import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
32import org.onlab.util.KryoNamespace;
pier6c48dba2018-11-27 11:23:50 -080033import org.onosproject.cluster.ClusterService;
34import org.onosproject.cluster.LeadershipService;
35import org.onosproject.cluster.NodeId;
Charles Chan4e87b3e2018-06-19 20:31:57 -070036import org.onosproject.codec.CodecService;
37import org.onosproject.core.ApplicationId;
38import org.onosproject.core.CoreService;
39import org.onosproject.mastership.MastershipService;
40import org.onosproject.net.ConnectPoint;
41import org.onosproject.net.DeviceId;
jayakumarthazhath46945b62018-10-01 00:51:54 +053042import org.onosproject.net.Host;
43import org.onosproject.net.HostLocation;
Charles Chan4e87b3e2018-06-19 20:31:57 -070044import org.onosproject.net.PortNumber;
45import org.onosproject.net.config.NetworkConfigService;
46import org.onosproject.net.device.DeviceEvent;
47import org.onosproject.net.device.DeviceListener;
48import org.onosproject.net.device.DeviceService;
49import org.onosproject.net.flow.DefaultTrafficSelector;
50import org.onosproject.net.flow.DefaultTrafficTreatment;
51import org.onosproject.net.flow.TrafficSelector;
52import org.onosproject.net.flow.TrafficTreatment;
53import org.onosproject.net.flow.criteria.Criteria;
54import org.onosproject.net.flowobjective.DefaultFilteringObjective;
55import org.onosproject.net.flowobjective.DefaultForwardingObjective;
56import org.onosproject.net.flowobjective.DefaultNextObjective;
57import org.onosproject.net.flowobjective.DefaultObjectiveContext;
58import org.onosproject.net.flowobjective.FilteringObjective;
59import org.onosproject.net.flowobjective.FlowObjectiveService;
60import org.onosproject.net.flowobjective.ForwardingObjective;
61import org.onosproject.net.flowobjective.NextObjective;
62import org.onosproject.net.flowobjective.Objective;
63import org.onosproject.net.flowobjective.ObjectiveContext;
64import org.onosproject.net.flowobjective.ObjectiveError;
jayakumarthazhath46945b62018-10-01 00:51:54 +053065import org.onosproject.net.host.HostEvent;
66import org.onosproject.net.host.HostListener;
67import org.onosproject.net.host.HostService;
68import org.onosproject.net.intf.InterfaceService;
Charles Chan4e87b3e2018-06-19 20:31:57 -070069import org.onosproject.segmentrouting.SegmentRoutingService;
jayakumarthazhath46945b62018-10-01 00:51:54 +053070import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan4e87b3e2018-06-19 20:31:57 -070071import org.onosproject.segmentrouting.xconnect.api.XconnectCodec;
72import org.onosproject.segmentrouting.xconnect.api.XconnectDesc;
73import org.onosproject.segmentrouting.xconnect.api.XconnectKey;
74import org.onosproject.segmentrouting.xconnect.api.XconnectService;
75import org.onosproject.store.serializers.KryoNamespaces;
76import org.onosproject.store.service.ConsistentMap;
77import org.onosproject.store.service.MapEvent;
78import org.onosproject.store.service.MapEventListener;
79import org.onosproject.store.service.Serializer;
80import org.onosproject.store.service.StorageService;
81import org.onosproject.store.service.Versioned;
82import org.slf4j.Logger;
83import org.slf4j.LoggerFactory;
84
85import java.io.Serializable;
jayakumarthazhath46945b62018-10-01 00:51:54 +053086import java.util.Collections;
87import java.util.List;
jayakumarthazhath46945b62018-10-01 00:51:54 +053088import java.util.Optional;
Charles Chan4e87b3e2018-06-19 20:31:57 -070089import java.util.Set;
90import java.util.concurrent.CompletableFuture;
Charles Chan1eec6252018-08-07 12:48:36 -070091import java.util.concurrent.ExecutorService;
92import java.util.concurrent.Executors;
Charles Chan4e87b3e2018-06-19 20:31:57 -070093import java.util.function.BiConsumer;
94import java.util.function.Consumer;
95import java.util.stream.Collectors;
96
Charles Chan1eec6252018-08-07 12:48:36 -070097import static org.onlab.util.Tools.groupedThreads;
98
Charles Chan4e87b3e2018-06-19 20:31:57 -070099@Service
100@Component(immediate = true)
101public class XconnectManager implements XconnectService {
102 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
103 private CoreService coreService;
104
105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
106 private CodecService codecService;
107
108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
109 private StorageService storageService;
110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
112 public NetworkConfigService netCfgService;
113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 public DeviceService deviceService;
116
117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 public FlowObjectiveService flowObjectiveService;
119
120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
pier6c48dba2018-11-27 11:23:50 -0800121 private LeadershipService leadershipService;
122
123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
124 private ClusterService clusterService;
125
126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan4e87b3e2018-06-19 20:31:57 -0700127 public MastershipService mastershipService;
128
129 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
130 public SegmentRoutingService srService;
131
jayakumarthazhath46945b62018-10-01 00:51:54 +0530132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
133 public InterfaceService interfaceService;
134
135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
136 HostService hostService;
137
Charles Chan4e87b3e2018-06-19 20:31:57 -0700138 private static final String APP_NAME = "org.onosproject.xconnect";
pier6c48dba2018-11-27 11:23:50 -0800139 private static final String ERROR_NOT_LEADER = "Not leader controller";
Charles Chan4e87b3e2018-06-19 20:31:57 -0700140
141 private static Logger log = LoggerFactory.getLogger(XconnectManager.class);
142
143 private ApplicationId appId;
144 private ConsistentMap<XconnectKey, Set<PortNumber>> xconnectStore;
Charles Chan263e7d92018-09-21 11:29:12 -0700145 private ConsistentMap<XconnectKey, Integer> xconnectNextObjStore;
Charles Chan4e87b3e2018-06-19 20:31:57 -0700146
jayakumarthazhath46945b62018-10-01 00:51:54 +0530147 private ConsistentMap<VlanNextObjectiveStoreKey, Integer> xconnectMulticastNextStore;
148 private ConsistentMap<VlanNextObjectiveStoreKey, List<PortNumber>> xconnectMulticastPortsStore;
149
Charles Chan4e87b3e2018-06-19 20:31:57 -0700150 private final MapEventListener<XconnectKey, Set<PortNumber>> xconnectListener = new XconnectMapListener();
pier6c48dba2018-11-27 11:23:50 -0800151 private ExecutorService xConnectExecutor;
Charles Chan4e87b3e2018-06-19 20:31:57 -0700152
pier6c48dba2018-11-27 11:23:50 -0800153 private final DeviceListener deviceListener = new InternalDeviceListener();
Charles Chan1eec6252018-08-07 12:48:36 -0700154 private ExecutorService deviceEventExecutor;
155
jayakumarthazhath46945b62018-10-01 00:51:54 +0530156 private final HostListener hostListener = new InternalHostListener();
157 private ExecutorService hostEventExecutor;
158
Charles Chan4e87b3e2018-06-19 20:31:57 -0700159 @Activate
160 void activate() {
161 appId = coreService.registerApplication(APP_NAME);
162 codecService.registerCodec(XconnectDesc.class, new XconnectCodec());
163
164 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
165 .register(KryoNamespaces.API)
Charles Chan397398c2018-07-23 12:53:16 -0700166 .register(XconnectManager.class)
jayakumarthazhath46945b62018-10-01 00:51:54 +0530167 .register(XconnectKey.class)
168 .register(VlanNextObjectiveStoreKey.class);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700169
170 xconnectStore = storageService.<XconnectKey, Set<PortNumber>>consistentMapBuilder()
171 .withName("onos-sr-xconnect")
172 .withRelaxedReadConsistency()
173 .withSerializer(Serializer.using(serializer.build()))
174 .build();
pier6c48dba2018-11-27 11:23:50 -0800175 xConnectExecutor = Executors.newSingleThreadScheduledExecutor(
176 groupedThreads("sr-xconnect-event", "%d", log));
177 xconnectStore.addListener(xconnectListener, xConnectExecutor);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700178
Charles Chan263e7d92018-09-21 11:29:12 -0700179 xconnectNextObjStore = storageService.<XconnectKey, Integer>consistentMapBuilder()
Charles Chan4e87b3e2018-06-19 20:31:57 -0700180 .withName("onos-sr-xconnect-next")
181 .withRelaxedReadConsistency()
182 .withSerializer(Serializer.using(serializer.build()))
183 .build();
184
jayakumarthazhath46945b62018-10-01 00:51:54 +0530185 xconnectMulticastNextStore = storageService.<VlanNextObjectiveStoreKey, Integer>consistentMapBuilder()
186 .withName("onos-sr-xconnect-l2multicast-next")
187 .withSerializer(Serializer.using(serializer.build()))
188 .build();
189 xconnectMulticastPortsStore = storageService.<VlanNextObjectiveStoreKey, List<PortNumber>>consistentMapBuilder()
190 .withName("onos-sr-xconnect-l2multicast-ports")
191 .withSerializer(Serializer.using(serializer.build()))
192 .build();
193
Charles Chan1eec6252018-08-07 12:48:36 -0700194 deviceEventExecutor = Executors.newSingleThreadScheduledExecutor(
195 groupedThreads("sr-xconnect-device-event", "%d", log));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700196 deviceService.addListener(deviceListener);
197
jayakumarthazhath46945b62018-10-01 00:51:54 +0530198 hostEventExecutor = Executors.newSingleThreadExecutor(
199 groupedThreads("sr-xconnect-host-event", "%d", log));
jayakumarthazhath46945b62018-10-01 00:51:54 +0530200 hostService.addListener(hostListener);
201
Charles Chan4e87b3e2018-06-19 20:31:57 -0700202 log.info("Started");
203 }
204
205 @Deactivate
206 void deactivate() {
207 xconnectStore.removeListener(xconnectListener);
208 deviceService.removeListener(deviceListener);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530209 hostService.removeListener(hostListener);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700210 codecService.unregisterCodec(XconnectDesc.class);
211
Charles Chan1eec6252018-08-07 12:48:36 -0700212 deviceEventExecutor.shutdown();
jayakumarthazhath46945b62018-10-01 00:51:54 +0530213 hostEventExecutor.shutdown();
pier6c48dba2018-11-27 11:23:50 -0800214 xConnectExecutor.shutdown();
Charles Chan1eec6252018-08-07 12:48:36 -0700215
Charles Chan4e87b3e2018-06-19 20:31:57 -0700216 log.info("Stopped");
217 }
218
219 @Override
220 public void addOrUpdateXconnect(DeviceId deviceId, VlanId vlanId, Set<PortNumber> ports) {
221 log.info("Adding or updating xconnect. deviceId={}, vlanId={}, ports={}",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530222 deviceId, vlanId, ports);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700223 final XconnectKey key = new XconnectKey(deviceId, vlanId);
224 xconnectStore.put(key, ports);
225 }
226
227 @Override
228 public void removeXonnect(DeviceId deviceId, VlanId vlanId) {
229 log.info("Removing xconnect. deviceId={}, vlanId={}",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530230 deviceId, vlanId);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700231 final XconnectKey key = new XconnectKey(deviceId, vlanId);
232 xconnectStore.remove(key);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530233
234 // Cleanup multicasting support, if any.
235 srService.getPairDeviceId(deviceId).ifPresent(pairDeviceId -> {
236 cleanupL2MulticastRule(pairDeviceId, srService.getPairLocalPort(pairDeviceId).get(), vlanId, true);
237 });
238
Charles Chan4e87b3e2018-06-19 20:31:57 -0700239 }
240
241 @Override
242 public Set<XconnectDesc> getXconnects() {
243 return xconnectStore.asJavaMap().entrySet().stream()
244 .map(e -> new XconnectDesc(e.getKey(), e.getValue()))
245 .collect(Collectors.toSet());
246 }
247
248 @Override
249 public boolean hasXconnect(ConnectPoint cp) {
pier6c48dba2018-11-27 11:23:50 -0800250 return getXconnects().stream().anyMatch(desc -> desc.key().deviceId().equals(cp.deviceId())
251 && desc.ports().contains(cp.port())
Charles Chan4e87b3e2018-06-19 20:31:57 -0700252 );
253 }
254
Charles Chan1fa010c2018-08-19 19:21:46 -0700255 @Override
jayakumarthazhath46945b62018-10-01 00:51:54 +0530256 public List<VlanId> getXconnectVlans(DeviceId deviceId, PortNumber port) {
257 return getXconnects().stream()
258 .filter(desc -> desc.key().deviceId().equals(deviceId) && desc.ports().contains(port))
pier6c48dba2018-11-27 11:23:50 -0800259 .map(desc -> desc.key().vlanId())
jayakumarthazhath46945b62018-10-01 00:51:54 +0530260 .collect(Collectors.toList());
261 }
262
263 @Override
264 public boolean isXconnectVlan(DeviceId deviceId, VlanId vlanId) {
pier6c48dba2018-11-27 11:23:50 -0800265 XconnectKey key = new XconnectKey(deviceId, vlanId);
266 return Versioned.valueOrNull(xconnectStore.get(key)) != null;
jayakumarthazhath46945b62018-10-01 00:51:54 +0530267 }
268
269 @Override
Charles Chan263e7d92018-09-21 11:29:12 -0700270 public ImmutableMap<XconnectKey, Integer> getNext() {
Charles Chan1fa010c2018-08-19 19:21:46 -0700271 if (xconnectNextObjStore != null) {
272 return ImmutableMap.copyOf(xconnectNextObjStore.asJavaMap());
273 } else {
274 return ImmutableMap.of();
275 }
276 }
277
278 @Override
pier6c48dba2018-11-27 11:23:50 -0800279 public int getNextId(DeviceId deviceId, VlanId vlanId) {
280 return Versioned.valueOrElse(xconnectNextObjStore.get(new XconnectKey(deviceId, vlanId)), -1);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530281 }
282
283 @Override
Charles Chan1fa010c2018-08-19 19:21:46 -0700284 public void removeNextId(int nextId) {
285 xconnectNextObjStore.entrySet().forEach(e -> {
Charles Chan263e7d92018-09-21 11:29:12 -0700286 if (e.getValue().value() == nextId) {
Charles Chan1fa010c2018-08-19 19:21:46 -0700287 xconnectNextObjStore.remove(e.getKey());
288 }
289 });
290 }
291
Charles Chan4e87b3e2018-06-19 20:31:57 -0700292 private class XconnectMapListener implements MapEventListener<XconnectKey, Set<PortNumber>> {
293 @Override
294 public void event(MapEvent<XconnectKey, Set<PortNumber>> event) {
295 XconnectKey key = event.key();
296 Versioned<Set<PortNumber>> ports = event.newValue();
297 Versioned<Set<PortNumber>> oldPorts = event.oldValue();
298
299 switch (event.type()) {
300 case INSERT:
301 populateXConnect(key, ports.value());
302 break;
303 case UPDATE:
304 updateXConnect(key, oldPorts.value(), ports.value());
305 break;
306 case REMOVE:
307 revokeXConnect(key, oldPorts.value());
308 break;
309 default:
310 break;
311 }
312 }
313 }
314
315 private class InternalDeviceListener implements DeviceListener {
pier6c48dba2018-11-27 11:23:50 -0800316 // Offload the execution to an executor and then process the event
317 // if this instance is the leader of the device
Charles Chan4e87b3e2018-06-19 20:31:57 -0700318 @Override
319 public void event(DeviceEvent event) {
Charles Chan1eec6252018-08-07 12:48:36 -0700320 deviceEventExecutor.execute(() -> {
321 DeviceId deviceId = event.subject().id();
pier6c48dba2018-11-27 11:23:50 -0800322 // Just skip if we are not the leader
323 if (!isLocalLeader(deviceId)) {
324 log.debug("Not the leader of {}. Skip event {}", deviceId, event);
Charles Chan1eec6252018-08-07 12:48:36 -0700325 return;
326 }
pier6c48dba2018-11-27 11:23:50 -0800327 // Populate or revoke according to the device availability
328 if (deviceService.isAvailable(deviceId)) {
329 init(deviceId);
330 } else {
331 cleanup(deviceId);
Charles Chan1eec6252018-08-07 12:48:36 -0700332 }
333 });
Charles Chan4e87b3e2018-06-19 20:31:57 -0700334 }
pier6c48dba2018-11-27 11:23:50 -0800335 // We want to manage only a subset of events and if we are the leader
336 @Override
337 public boolean isRelevant(DeviceEvent event) {
338 return event.type() == DeviceEvent.Type.DEVICE_ADDED ||
339 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
340 event.type() == DeviceEvent.Type.DEVICE_UPDATED;
341 }
Charles Chan4e87b3e2018-06-19 20:31:57 -0700342 }
343
jayakumarthazhath46945b62018-10-01 00:51:54 +0530344 private class InternalHostListener implements HostListener {
345 @Override
346 public void event(HostEvent event) {
347 hostEventExecutor.execute(() -> {
348
349 switch (event.type()) {
350 case HOST_MOVED:
351 log.trace("Processing host event {}", event);
352
353 Host host = event.subject();
354 Set<HostLocation> prevLocations = event.prevSubject().locations();
355 Set<HostLocation> newLocations = host.locations();
356
357 // Dual-home host port failure
358 // For each old location, in failed and paired devices update L2 vlan groups
359 Sets.difference(prevLocations, newLocations).forEach(prevLocation -> {
360
361 Optional<DeviceId> pairDeviceId = srService.getPairDeviceId(prevLocation.deviceId());
362 Optional<PortNumber> pairLocalPort = srService.getPairLocalPort(prevLocation.deviceId());
363
364 if (pairDeviceId.isPresent() && pairLocalPort.isPresent() && newLocations.stream()
365 .anyMatch(location -> location.deviceId().equals(pairDeviceId.get())) &&
366 hasXconnect(new ConnectPoint(prevLocation.deviceId(), prevLocation.port()))) {
367
368 List<VlanId> xconnectVlans = getXconnectVlans(prevLocation.deviceId(),
369 prevLocation.port());
370 xconnectVlans.forEach(xconnectVlan -> {
371 // Add single-home host into L2 multicast group at paired device side.
372 // Also append ACL rule to forward traffic from paired port to L2 multicast group.
373 newLocations.stream()
374 .filter(location -> location.deviceId().equals(pairDeviceId.get()))
375 .forEach(location -> populateL2Multicast(location.deviceId(),
376 srService.getPairLocalPort(
377 location.deviceId()).get(),
378 xconnectVlan,
379 Collections.singletonList(
380 location.port())));
pier6c48dba2018-11-27 11:23:50 -0800381 // Ensure pair-port attached to xconnect vlan flooding group
382 // at dual home failed device.
jayakumarthazhath46945b62018-10-01 00:51:54 +0530383 updateL2Flooding(prevLocation.deviceId(), pairLocalPort.get(), xconnectVlan, true);
384 });
385 }
386 });
387
388 // Dual-home host port restoration
389 // For each new location, reverse xconnect loop prevention groups.
390 Sets.difference(newLocations, prevLocations).forEach(newLocation -> {
391 final Optional<DeviceId> pairDeviceId = srService.getPairDeviceId(newLocation.deviceId());
392 Optional<PortNumber> pairLocalPort = srService.getPairLocalPort(newLocation.deviceId());
393 if (pairDeviceId.isPresent() && pairLocalPort.isPresent() &&
394 hasXconnect((new ConnectPoint(newLocation.deviceId(), newLocation.port())))) {
395
396 List<VlanId> xconnectVlans = getXconnectVlans(newLocation.deviceId(),
397 newLocation.port());
398 xconnectVlans.forEach(xconnectVlan -> {
399 // Remove recovered dual homed port from vlan L2 multicast group
400 prevLocations.stream()
401 .filter(prevLocation -> prevLocation.deviceId().equals(pairDeviceId.get()))
pier6c48dba2018-11-27 11:23:50 -0800402 .forEach(prevLocation -> revokeL2Multicast(
403 prevLocation.deviceId(),
404 xconnectVlan,
405 Collections.singletonList(newLocation.port()))
jayakumarthazhath46945b62018-10-01 00:51:54 +0530406 );
407
pier6c48dba2018-11-27 11:23:50 -0800408 // Remove pair-port from vlan's flooding group at dual home
409 // restored device, if needed.
410 if (!hasAccessPortInMulticastGroup(new VlanNextObjectiveStoreKey(
411 newLocation.deviceId(), xconnectVlan), pairLocalPort.get())) {
jayakumarthazhath46945b62018-10-01 00:51:54 +0530412 updateL2Flooding(newLocation.deviceId(),
413 pairLocalPort.get(),
414 xconnectVlan,
415 false);
416
417 // Clean L2 multicast group at pair-device; also update store.
418 cleanupL2MulticastRule(pairDeviceId.get(),
419 srService.getPairLocalPort(pairDeviceId.get()).get(),
420 xconnectVlan,
421 false);
422 }
423 });
424 }
425 });
426 break;
427
428 default:
429 log.warn("Unsupported host event type: {} received. Ignoring.", event.type());
430 break;
431 }
432 });
433 }
434 }
435
Charles Chan263e7d92018-09-21 11:29:12 -0700436 private void init(DeviceId deviceId) {
Charles Chan4e87b3e2018-06-19 20:31:57 -0700437 getXconnects().stream()
438 .filter(desc -> desc.key().deviceId().equals(deviceId))
439 .forEach(desc -> populateXConnect(desc.key(), desc.ports()));
440 }
441
Charles Chan263e7d92018-09-21 11:29:12 -0700442 private void cleanup(DeviceId deviceId) {
Charles Chan4e87b3e2018-06-19 20:31:57 -0700443 xconnectNextObjStore.entrySet().stream()
444 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
445 .forEach(entry -> xconnectNextObjStore.remove(entry.getKey()));
446 log.debug("{} is removed from xConnectNextObjStore", deviceId);
447 }
448
449 /**
450 * Populates XConnect groups and flows for given key.
451 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530452 * @param key XConnect key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700453 * @param ports a set of ports to be cross-connected
454 */
455 private void populateXConnect(XconnectKey key, Set<PortNumber> ports) {
pier6c48dba2018-11-27 11:23:50 -0800456 if (!isLocalLeader(key.deviceId())) {
457 log.debug("Abort populating XConnect {}: {}", key, ERROR_NOT_LEADER);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700458 return;
459 }
460
Charles Chan4e87b3e2018-06-19 20:31:57 -0700461 populateFilter(key, ports);
462 populateFwd(key, populateNext(key, ports));
463 populateAcl(key);
464 }
465
466 /**
467 * Populates filtering objectives for given XConnect.
468 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530469 * @param key XConnect store key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700470 * @param ports XConnect ports
471 */
472 private void populateFilter(XconnectKey key, Set<PortNumber> ports) {
473 ports.forEach(port -> {
474 FilteringObjective.Builder filtObjBuilder = filterObjBuilder(key, port);
475 ObjectiveContext context = new DefaultObjectiveContext(
476 (objective) -> log.debug("XConnect FilterObj for {} on port {} populated",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530477 key, port),
Charles Chan4e87b3e2018-06-19 20:31:57 -0700478 (objective, error) ->
479 log.warn("Failed to populate XConnect FilterObj for {} on port {}: {}",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530480 key, port, error));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700481 flowObjectiveService.filter(key.deviceId(), filtObjBuilder.add(context));
482 });
483 }
484
485 /**
486 * Populates next objectives for given XConnect.
487 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530488 * @param key XConnect store key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700489 * @param ports XConnect ports
490 */
Charles Chan263e7d92018-09-21 11:29:12 -0700491 private int populateNext(XconnectKey key, Set<PortNumber> ports) {
pier6c48dba2018-11-27 11:23:50 -0800492 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
493 if (nextId != -1) {
Charles Chan263e7d92018-09-21 11:29:12 -0700494 log.debug("NextObj for {} found, id={}", key, nextId);
495 return nextId;
Charles Chan4e87b3e2018-06-19 20:31:57 -0700496 } else {
497 NextObjective.Builder nextObjBuilder = nextObjBuilder(key, ports);
498 ObjectiveContext nextContext = new DefaultObjectiveContext(
499 // To serialize this with kryo
500 (Serializable & Consumer<Objective>) (objective) ->
501 log.debug("XConnect NextObj for {} added", key),
Charles Chan1dbadbd2018-08-23 14:30:33 -0700502 (Serializable & BiConsumer<Objective, ObjectiveError>) (objective, error) -> {
503 log.warn("Failed to add XConnect NextObj for {}: {}", key, error);
504 srService.invalidateNextObj(objective.id());
505 });
Charles Chan263e7d92018-09-21 11:29:12 -0700506 NextObjective nextObj = nextObjBuilder.add(nextContext);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700507 flowObjectiveService.next(key.deviceId(), nextObj);
Charles Chan263e7d92018-09-21 11:29:12 -0700508 xconnectNextObjStore.put(key, nextObj.id());
Charles Chan4e87b3e2018-06-19 20:31:57 -0700509 log.debug("NextObj for {} not found. Creating new NextObj with id={}", key, nextObj.id());
Charles Chan263e7d92018-09-21 11:29:12 -0700510 return nextObj.id();
Charles Chan4e87b3e2018-06-19 20:31:57 -0700511 }
Charles Chan4e87b3e2018-06-19 20:31:57 -0700512 }
513
514 /**
515 * Populates bridging forwarding objectives for given XConnect.
516 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530517 * @param key XConnect store key
Charles Chan263e7d92018-09-21 11:29:12 -0700518 * @param nextId next objective id
Charles Chan4e87b3e2018-06-19 20:31:57 -0700519 */
Charles Chan263e7d92018-09-21 11:29:12 -0700520 private void populateFwd(XconnectKey key, int nextId) {
521 ForwardingObjective.Builder fwdObjBuilder = fwdObjBuilder(key, nextId);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700522 ObjectiveContext fwdContext = new DefaultObjectiveContext(
523 (objective) -> log.debug("XConnect FwdObj for {} populated", key),
524 (objective, error) ->
525 log.warn("Failed to populate XConnect FwdObj for {}: {}", key, error));
526 flowObjectiveService.forward(key.deviceId(), fwdObjBuilder.add(fwdContext));
527 }
528
529 /**
530 * Populates ACL forwarding objectives for given XConnect.
531 *
532 * @param key XConnect store key
533 */
534 private void populateAcl(XconnectKey key) {
535 ForwardingObjective.Builder aclObjBuilder = aclObjBuilder(key.vlanId());
536 ObjectiveContext aclContext = new DefaultObjectiveContext(
537 (objective) -> log.debug("XConnect AclObj for {} populated", key),
538 (objective, error) ->
539 log.warn("Failed to populate XConnect AclObj for {}: {}", key, error));
540 flowObjectiveService.forward(key.deviceId(), aclObjBuilder.add(aclContext));
541 }
542
543 /**
544 * Revokes XConnect groups and flows for given key.
545 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530546 * @param key XConnect key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700547 * @param ports XConnect ports
548 */
549 private void revokeXConnect(XconnectKey key, Set<PortNumber> ports) {
pier6c48dba2018-11-27 11:23:50 -0800550 if (!isLocalLeader(key.deviceId())) {
551 log.debug("Abort revoking XConnect {}: {}", key, ERROR_NOT_LEADER);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700552 return;
553 }
554
Charles Chan4e87b3e2018-06-19 20:31:57 -0700555 revokeFilter(key, ports);
pier6c48dba2018-11-27 11:23:50 -0800556 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
557 if (nextId != -1) {
Charles Chan263e7d92018-09-21 11:29:12 -0700558 revokeFwd(key, nextId, null);
559 revokeNext(key, ports, nextId, null);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700560 } else {
561 log.warn("NextObj for {} does not exist in the store.", key);
562 }
563 revokeAcl(key);
564 }
565
566 /**
567 * Revokes filtering objectives for given XConnect.
568 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530569 * @param key XConnect store key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700570 * @param ports XConnect ports
571 */
572 private void revokeFilter(XconnectKey key, Set<PortNumber> ports) {
573 ports.forEach(port -> {
574 FilteringObjective.Builder filtObjBuilder = filterObjBuilder(key, port);
575 ObjectiveContext context = new DefaultObjectiveContext(
576 (objective) -> log.debug("XConnect FilterObj for {} on port {} revoked",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530577 key, port),
Charles Chan4e87b3e2018-06-19 20:31:57 -0700578 (objective, error) ->
579 log.warn("Failed to revoke XConnect FilterObj for {} on port {}: {}",
jayakumarthazhath46945b62018-10-01 00:51:54 +0530580 key, port, error));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700581 flowObjectiveService.filter(key.deviceId(), filtObjBuilder.remove(context));
582 });
583 }
584
585 /**
586 * Revokes next objectives for given XConnect.
587 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530588 * @param key XConnect store key
589 * @param ports ports in the XConnect
590 * @param nextId next objective id
Charles Chan4e87b3e2018-06-19 20:31:57 -0700591 * @param nextFuture completable future for this next objective operation
592 */
Charles Chan263e7d92018-09-21 11:29:12 -0700593 private void revokeNext(XconnectKey key, Set<PortNumber> ports, int nextId,
Charles Chan4e87b3e2018-06-19 20:31:57 -0700594 CompletableFuture<ObjectiveError> nextFuture) {
595 ObjectiveContext context = new ObjectiveContext() {
596 @Override
597 public void onSuccess(Objective objective) {
598 log.debug("Previous NextObj for {} removed", key);
599 if (nextFuture != null) {
600 nextFuture.complete(null);
601 }
602 }
603
604 @Override
605 public void onError(Objective objective, ObjectiveError error) {
606 log.warn("Failed to remove previous NextObj for {}: {}", key, error);
607 if (nextFuture != null) {
608 nextFuture.complete(error);
609 }
Charles Chan1dbadbd2018-08-23 14:30:33 -0700610 srService.invalidateNextObj(objective.id());
Charles Chan4e87b3e2018-06-19 20:31:57 -0700611 }
612 };
Charles Chan263e7d92018-09-21 11:29:12 -0700613 flowObjectiveService.next(key.deviceId(), nextObjBuilder(key, ports, nextId).remove(context));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700614 xconnectNextObjStore.remove(key);
615 }
616
617 /**
618 * Revokes bridging forwarding objectives for given XConnect.
619 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530620 * @param key XConnect store key
621 * @param nextId next objective id
Charles Chan4e87b3e2018-06-19 20:31:57 -0700622 * @param fwdFuture completable future for this forwarding objective operation
623 */
Charles Chan263e7d92018-09-21 11:29:12 -0700624 private void revokeFwd(XconnectKey key, int nextId, CompletableFuture<ObjectiveError> fwdFuture) {
625 ForwardingObjective.Builder fwdObjBuilder = fwdObjBuilder(key, nextId);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700626 ObjectiveContext context = new ObjectiveContext() {
627 @Override
628 public void onSuccess(Objective objective) {
629 log.debug("Previous FwdObj for {} removed", key);
630 if (fwdFuture != null) {
631 fwdFuture.complete(null);
632 }
633 }
634
635 @Override
636 public void onError(Objective objective, ObjectiveError error) {
637 log.warn("Failed to remove previous FwdObj for {}: {}", key, error);
638 if (fwdFuture != null) {
639 fwdFuture.complete(error);
640 }
641 }
642 };
643 flowObjectiveService.forward(key.deviceId(), fwdObjBuilder.remove(context));
644 }
645
646 /**
647 * Revokes ACL forwarding objectives for given XConnect.
648 *
649 * @param key XConnect store key
650 */
651 private void revokeAcl(XconnectKey key) {
652 ForwardingObjective.Builder aclObjBuilder = aclObjBuilder(key.vlanId());
653 ObjectiveContext aclContext = new DefaultObjectiveContext(
654 (objective) -> log.debug("XConnect AclObj for {} populated", key),
655 (objective, error) ->
656 log.warn("Failed to populate XConnect AclObj for {}: {}", key, error));
657 flowObjectiveService.forward(key.deviceId(), aclObjBuilder.remove(aclContext));
658 }
659
660 /**
661 * Updates XConnect groups and flows for given key.
662 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530663 * @param key XConnect key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700664 * @param prevPorts previous XConnect ports
jayakumarthazhath46945b62018-10-01 00:51:54 +0530665 * @param ports new XConnect ports
Charles Chan4e87b3e2018-06-19 20:31:57 -0700666 */
667 private void updateXConnect(XconnectKey key, Set<PortNumber> prevPorts,
668 Set<PortNumber> ports) {
pier6c48dba2018-11-27 11:23:50 -0800669 if (!isLocalLeader(key.deviceId())) {
670 log.debug("Abort updating XConnect {}: {}", key, ERROR_NOT_LEADER);
671 return;
672 }
Charles Chan4e87b3e2018-06-19 20:31:57 -0700673 // NOTE: ACL flow doesn't include port information. No need to update it.
674 // Pair port is built-in and thus not going to change. No need to update it.
675
676 // remove old filter
677 prevPorts.stream().filter(port -> !ports.contains(port)).forEach(port ->
jayakumarthazhath46945b62018-10-01 00:51:54 +0530678 revokeFilter(key,
679 ImmutableSet.of(port)));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700680 // install new filter
681 ports.stream().filter(port -> !prevPorts.contains(port)).forEach(port ->
jayakumarthazhath46945b62018-10-01 00:51:54 +0530682 populateFilter(key,
683 ImmutableSet.of(port)));
Charles Chan4e87b3e2018-06-19 20:31:57 -0700684
685 CompletableFuture<ObjectiveError> fwdFuture = new CompletableFuture<>();
686 CompletableFuture<ObjectiveError> nextFuture = new CompletableFuture<>();
687
pier6c48dba2018-11-27 11:23:50 -0800688 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
689 if (nextId != -1) {
Charles Chan263e7d92018-09-21 11:29:12 -0700690 revokeFwd(key, nextId, fwdFuture);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700691
692 fwdFuture.thenAcceptAsync(fwdStatus -> {
693 if (fwdStatus == null) {
694 log.debug("Fwd removed. Now remove group {}", key);
Charles Chan263e7d92018-09-21 11:29:12 -0700695 revokeNext(key, prevPorts, nextId, nextFuture);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700696 }
697 });
698
699 nextFuture.thenAcceptAsync(nextStatus -> {
700 if (nextStatus == null) {
701 log.debug("Installing new group and flow for {}", key);
702 populateFwd(key, populateNext(key, ports));
703 }
704 });
705 } else {
706 log.warn("NextObj for {} does not exist in the store.", key);
707 }
708 }
709
710 /**
Charles Chan263e7d92018-09-21 11:29:12 -0700711 * Creates a next objective builder for XConnect with given nextId.
Charles Chan4e87b3e2018-06-19 20:31:57 -0700712 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530713 * @param key XConnect key
714 * @param ports set of XConnect ports
Charles Chan263e7d92018-09-21 11:29:12 -0700715 * @param nextId next objective id
Charles Chan4e87b3e2018-06-19 20:31:57 -0700716 * @return next objective builder
717 */
Charles Chan263e7d92018-09-21 11:29:12 -0700718 private NextObjective.Builder nextObjBuilder(XconnectKey key, Set<PortNumber> ports, int nextId) {
Charles Chan4e87b3e2018-06-19 20:31:57 -0700719 TrafficSelector metadata =
720 DefaultTrafficSelector.builder().matchVlanId(key.vlanId()).build();
721 NextObjective.Builder nextObjBuilder = DefaultNextObjective
722 .builder().withId(nextId)
723 .withType(NextObjective.Type.BROADCAST).fromApp(appId)
724 .withMeta(metadata);
725 ports.forEach(port -> {
726 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
727 tBuilder.setOutput(port);
728 nextObjBuilder.addTreatment(tBuilder.build());
729 });
730 return nextObjBuilder;
731 }
732
733 /**
Charles Chan263e7d92018-09-21 11:29:12 -0700734 * Creates a next objective builder for XConnect.
735 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530736 * @param key XConnect key
Charles Chan263e7d92018-09-21 11:29:12 -0700737 * @param ports set of XConnect ports
738 * @return next objective builder
739 */
740 private NextObjective.Builder nextObjBuilder(XconnectKey key, Set<PortNumber> ports) {
741 int nextId = flowObjectiveService.allocateNextId();
742 return nextObjBuilder(key, ports, nextId);
743 }
744
745
746 /**
Charles Chan4e87b3e2018-06-19 20:31:57 -0700747 * Creates a bridging forwarding objective builder for XConnect.
748 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530749 * @param key XConnect key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700750 * @param nextId next ID of the broadcast group for this XConnect key
751 * @return forwarding objective builder
752 */
753 private ForwardingObjective.Builder fwdObjBuilder(XconnectKey key, int nextId) {
754 /*
755 * Driver should treat objectives with MacAddress.NONE and !VlanId.NONE
756 * as the VLAN cross-connect broadcast rules
757 */
758 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
759 sbuilder.matchVlanId(key.vlanId());
760 sbuilder.matchEthDst(MacAddress.NONE);
761
762 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
763 fob.withFlag(ForwardingObjective.Flag.SPECIFIC)
764 .withSelector(sbuilder.build())
765 .nextStep(nextId)
766 .withPriority(XCONNECT_PRIORITY)
767 .fromApp(appId)
768 .makePermanent();
769 return fob;
770 }
771
772 /**
773 * Creates an ACL forwarding objective builder for XConnect.
774 *
775 * @param vlanId cross connect VLAN id
776 * @return forwarding objective builder
777 */
778 private ForwardingObjective.Builder aclObjBuilder(VlanId vlanId) {
779 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
780 sbuilder.matchVlanId(vlanId);
781
782 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
783
784 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
785 fob.withFlag(ForwardingObjective.Flag.VERSATILE)
786 .withSelector(sbuilder.build())
787 .withTreatment(tbuilder.build())
788 .withPriority(XCONNECT_ACL_PRIORITY)
789 .fromApp(appId)
790 .makePermanent();
791 return fob;
792 }
793
794 /**
795 * Creates a filtering objective builder for XConnect.
796 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530797 * @param key XConnect key
Charles Chan4e87b3e2018-06-19 20:31:57 -0700798 * @param port XConnect ports
799 * @return next objective builder
800 */
801 private FilteringObjective.Builder filterObjBuilder(XconnectKey key, PortNumber port) {
802 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
803 fob.withKey(Criteria.matchInPort(port))
804 .addCondition(Criteria.matchVlanId(key.vlanId()))
805 .addCondition(Criteria.matchEthDst(MacAddress.NONE))
806 .withPriority(XCONNECT_PRIORITY);
807 return fob.permit().fromApp(appId);
808 }
809
810 /**
jayakumarthazhath46945b62018-10-01 00:51:54 +0530811 * Updates L2 flooding groups; add pair link into L2 flooding group of given xconnect vlan.
Charles Chan4e87b3e2018-06-19 20:31:57 -0700812 *
jayakumarthazhath46945b62018-10-01 00:51:54 +0530813 * @param deviceId Device ID
814 * @param port Port details
815 * @param vlanId VLAN ID
816 * @param install Whether to add or revoke pair link addition to flooding group
Charles Chan4e87b3e2018-06-19 20:31:57 -0700817 */
pier6c48dba2018-11-27 11:23:50 -0800818 private void updateL2Flooding(DeviceId deviceId, PortNumber port, VlanId vlanId, boolean install) {
819 XconnectKey key = new XconnectKey(deviceId, vlanId);
820 // Ensure leadership on device
821 if (!isLocalLeader(deviceId)) {
822 log.debug("Abort updating L2Flood {}: {}", key, ERROR_NOT_LEADER);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530823 return;
Charles Chan4e87b3e2018-06-19 20:31:57 -0700824 }
jayakumarthazhath46945b62018-10-01 00:51:54 +0530825
826 // Locate L2 flooding group details for given xconnect vlan
pier6c48dba2018-11-27 11:23:50 -0800827 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530828 if (nextId == -1) {
829 log.debug("XConnect vlan {} broadcast group for device {} doesn't exists. " +
830 "Aborting pair group linking.", vlanId, deviceId);
831 return;
832 }
833
834 // Add pairing-port group to flooding group
835 TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
836 // treatment.popVlan();
837 treatment.setOutput(port);
838 ObjectiveContext context = new DefaultObjectiveContext(
839 (objective) ->
840 log.debug("Pair port added/removed to vlan {} next objective {} on {}",
841 vlanId, nextId, deviceId),
842 (objective, error) ->
843 log.warn("Failed adding/removing pair port to vlan {} next objective {} on {}." +
844 "Error : {}", vlanId, nextId, deviceId, error)
845 );
846 NextObjective.Builder vlanNextObjectiveBuilder = DefaultNextObjective.builder()
847 .withId(nextId)
848 .withType(NextObjective.Type.BROADCAST)
849 .fromApp(srService.appId())
850 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId).build())
851 .addTreatment(treatment.build());
852 if (install) {
853 flowObjectiveService.next(deviceId, vlanNextObjectiveBuilder.addToExisting(context));
854 } else {
855 flowObjectiveService.next(deviceId, vlanNextObjectiveBuilder.removeFromExisting(context));
856 }
857 log.debug("Submitted next objective {} for vlan: {} in device {}",
858 nextId, vlanId, deviceId);
Charles Chan4e87b3e2018-06-19 20:31:57 -0700859 }
jayakumarthazhath46945b62018-10-01 00:51:54 +0530860
861 /**
862 * Populate L2 multicast rule on given deviceId that matches given mac, given vlan and
863 * output to given port's L2 mulitcast group.
864 *
865 * @param deviceId Device ID
866 * @param pairPort Pair port number
867 * @param vlanId VLAN ID
868 * @param accessPorts List of access ports to be added into L2 multicast group
869 */
pier6c48dba2018-11-27 11:23:50 -0800870 private void populateL2Multicast(DeviceId deviceId, PortNumber pairPort,
871 VlanId vlanId, List<PortNumber> accessPorts) {
872 // Ensure enough rights to program pair device
873 if (!srService.shouldProgram(deviceId)) {
874 log.debug("Abort populate L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
875 return;
876 }
jayakumarthazhath46945b62018-10-01 00:51:54 +0530877
878 boolean multicastGroupExists = true;
879 int vlanMulticastNextId;
pier6c48dba2018-11-27 11:23:50 -0800880 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530881
882 // Step 1 : Populate single homed access ports into vlan's L2 multicast group
883 NextObjective.Builder vlanMulticastNextObjBuilder = DefaultNextObjective
884 .builder()
885 .withType(NextObjective.Type.BROADCAST)
886 .fromApp(srService.appId())
887 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId)
888 .matchEthDst(MacAddress.IPV4_MULTICAST).build());
pier6c48dba2018-11-27 11:23:50 -0800889 vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530890 if (vlanMulticastNextId == -1) {
891 // Vlan's L2 multicast group doesn't exist; create it, update store and add pair port as sub-group
892 multicastGroupExists = false;
893 vlanMulticastNextId = flowObjectiveService.allocateNextId();
pier6c48dba2018-11-27 11:23:50 -0800894 addMulticastGroupNextObjectiveId(key, vlanMulticastNextId);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530895 vlanMulticastNextObjBuilder.addTreatment(
896 DefaultTrafficTreatment.builder().popVlan().setOutput(pairPort).build()
897 );
898 }
899 vlanMulticastNextObjBuilder.withId(vlanMulticastNextId);
pier6c48dba2018-11-27 11:23:50 -0800900 int nextId = vlanMulticastNextId;
jayakumarthazhath46945b62018-10-01 00:51:54 +0530901 accessPorts.forEach(p -> {
902 TrafficTreatment.Builder egressAction = DefaultTrafficTreatment.builder();
903 // Do vlan popup action based on interface configuration
904 if (interfaceService.getInterfacesByPort(new ConnectPoint(deviceId, p))
905 .stream().noneMatch(i -> i.vlanTagged().contains(vlanId))) {
906 egressAction.popVlan();
907 }
908 egressAction.setOutput(p);
909 vlanMulticastNextObjBuilder.addTreatment(egressAction.build());
pier6c48dba2018-11-27 11:23:50 -0800910 addMulticastGroupPort(key, p);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530911 });
912 ObjectiveContext context = new DefaultObjectiveContext(
913 (objective) ->
914 log.debug("L2 multicast group installed/updated. "
915 + "NextObject Id {} on {} for subnet {} ",
916 nextId, deviceId, vlanId),
917 (objective, error) ->
918 log.warn("L2 multicast group failed to install/update. "
919 + " NextObject Id {} on {} for subnet {} : {}",
920 nextId, deviceId, vlanId, error)
921 );
922 if (!multicastGroupExists) {
923 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.add(context));
924
925 // Step 2 : Populate ACL rule; selector = vlan + pair-port, output = vlan L2 multicast group
926 TrafficSelector.Builder multicastSelector = DefaultTrafficSelector.builder();
927 multicastSelector.matchEthType(Ethernet.TYPE_VLAN);
928 multicastSelector.matchInPort(pairPort);
929 multicastSelector.matchVlanId(vlanId);
930 ForwardingObjective.Builder vlanMulticastForwardingObj = DefaultForwardingObjective.builder()
931 .withFlag(ForwardingObjective.Flag.VERSATILE)
932 .nextStep(vlanMulticastNextId)
933 .withSelector(multicastSelector.build())
934 .withPriority(100)
935 .fromApp(srService.appId())
936 .makePermanent();
937 context = new DefaultObjectiveContext(
938 (objective) -> log.debug("L2 multicasting versatile rule for device {}, port/vlan {}/{} populated",
939 deviceId,
940 pairPort,
941 vlanId),
942 (objective, error) -> log.warn("Failed to populate L2 multicasting versatile rule for device {}, " +
943 "ports/vlan {}/{}: {}", deviceId, pairPort, vlanId, error));
944 flowObjectiveService.forward(deviceId, vlanMulticastForwardingObj.add(context));
945 } else {
946 // L2_MULTICAST & BROADCAST are similar structure in subgroups; so going with BROADCAST type.
947 vlanMulticastNextObjBuilder.withType(NextObjective.Type.BROADCAST);
948 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.addToExisting(context));
949 }
950 }
951
952 /**
953 * Removes access ports from VLAN L2 multicast group on given deviceId.
954 *
955 * @param deviceId Device ID
jayakumarthazhath46945b62018-10-01 00:51:54 +0530956 * @param vlanId VLAN ID
957 * @param accessPorts List of access ports to be added into L2 multicast group
958 */
pier6c48dba2018-11-27 11:23:50 -0800959 private void revokeL2Multicast(DeviceId deviceId, VlanId vlanId, List<PortNumber> accessPorts) {
jayakumarthazhath46945b62018-10-01 00:51:54 +0530960 // Ensure enough rights to program pair device
961 if (!srService.shouldProgram(deviceId)) {
pier6c48dba2018-11-27 11:23:50 -0800962 log.debug("Abort revoke L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530963 return;
964 }
965
pier6c48dba2018-11-27 11:23:50 -0800966 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
967
968 int vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530969 if (vlanMulticastNextId == -1) {
970 return;
971 }
972 NextObjective.Builder vlanMulticastNextObjBuilder = DefaultNextObjective
973 .builder()
974 .withType(NextObjective.Type.BROADCAST)
975 .fromApp(srService.appId())
976 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId).build())
977 .withId(vlanMulticastNextId);
978 accessPorts.forEach(p -> {
979 TrafficTreatment.Builder egressAction = DefaultTrafficTreatment.builder();
980 // Do vlan popup action based on interface configuration
981 if (interfaceService.getInterfacesByPort(new ConnectPoint(deviceId, p))
982 .stream().noneMatch(i -> i.vlanTagged().contains(vlanId))) {
983 egressAction.popVlan();
984 }
985 egressAction.setOutput(p);
986 vlanMulticastNextObjBuilder.addTreatment(egressAction.build());
pier6c48dba2018-11-27 11:23:50 -0800987 removeMulticastGroupPort(key, p);
jayakumarthazhath46945b62018-10-01 00:51:54 +0530988 });
989 ObjectiveContext context = new DefaultObjectiveContext(
990 (objective) ->
991 log.debug("L2 multicast group installed/updated. "
992 + "NextObject Id {} on {} for subnet {} ",
993 vlanMulticastNextId, deviceId, vlanId),
994 (objective, error) ->
995 log.warn("L2 multicast group failed to install/update. "
996 + " NextObject Id {} on {} for subnet {} : {}",
997 vlanMulticastNextId, deviceId, vlanId, error)
998 );
999 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.removeFromExisting(context));
1000 }
1001
1002 /**
1003 * Cleans up VLAN L2 multicast group on given deviceId. ACL rules for the group will also be deleted.
1004 * Normally multicast group is not removed if it contains access ports; which can be forced
1005 * by "force" flag
1006 *
1007 * @param deviceId Device ID
1008 * @param pairPort Pair port number
1009 * @param vlanId VLAN ID
1010 * @param force Forceful removal
1011 */
1012 private void cleanupL2MulticastRule(DeviceId deviceId, PortNumber pairPort, VlanId vlanId, boolean force) {
1013
1014 // Ensure enough rights to program pair device
1015 if (!srService.shouldProgram(deviceId)) {
pier6c48dba2018-11-27 11:23:50 -08001016 log.debug("Abort cleanup L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301017 return;
1018 }
1019
pier6c48dba2018-11-27 11:23:50 -08001020 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
1021
jayakumarthazhath46945b62018-10-01 00:51:54 +05301022 // Ensure L2 multicast group doesn't contain access ports
pier6c48dba2018-11-27 11:23:50 -08001023 if (hasAccessPortInMulticastGroup(key, pairPort) && !force) {
jayakumarthazhath46945b62018-10-01 00:51:54 +05301024 return;
1025 }
1026
1027 // Load L2 multicast group details
pier6c48dba2018-11-27 11:23:50 -08001028 int vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301029 if (vlanMulticastNextId == -1) {
1030 return;
1031 }
1032
1033 // Step 1 : Clear ACL rule; selector = vlan + pair-port, output = vlan L2 multicast group
1034 TrafficSelector.Builder l2MulticastSelector = DefaultTrafficSelector.builder();
1035 l2MulticastSelector.matchEthType(Ethernet.TYPE_VLAN);
1036 l2MulticastSelector.matchInPort(pairPort);
1037 l2MulticastSelector.matchVlanId(vlanId);
1038 ForwardingObjective.Builder vlanMulticastForwardingObj = DefaultForwardingObjective.builder()
1039 .withFlag(ForwardingObjective.Flag.VERSATILE)
1040 .nextStep(vlanMulticastNextId)
1041 .withSelector(l2MulticastSelector.build())
1042 .withPriority(100)
1043 .fromApp(srService.appId())
1044 .makePermanent();
1045 ObjectiveContext context = new DefaultObjectiveContext(
1046 (objective) -> log.debug("L2 multicasting rule for device {}, port/vlan {}/{} deleted", deviceId,
1047 pairPort, vlanId),
1048 (objective, error) -> log.warn("Failed to delete L2 multicasting rule for device {}, " +
1049 "ports/vlan {}/{}: {}", deviceId, pairPort, vlanId, error));
1050 flowObjectiveService.forward(deviceId, vlanMulticastForwardingObj.remove(context));
1051
1052 // Step 2 : Clear L2 multicast group associated with vlan
1053 NextObjective.Builder l2MulticastGroupBuilder = DefaultNextObjective
1054 .builder()
1055 .withId(vlanMulticastNextId)
1056 .withType(NextObjective.Type.BROADCAST)
1057 .fromApp(srService.appId())
1058 .withMeta(DefaultTrafficSelector.builder()
1059 .matchVlanId(vlanId)
1060 .matchEthDst(MacAddress.IPV4_MULTICAST).build())
1061 .addTreatment(DefaultTrafficTreatment.builder().popVlan().setOutput(pairPort).build());
1062 context = new DefaultObjectiveContext(
1063 (objective) ->
1064 log.debug("L2 multicast group with NextObject Id {} deleted on {} for subnet {} ",
1065 vlanMulticastNextId, deviceId, vlanId),
1066 (objective, error) ->
1067 log.warn("L2 multicast group with NextObject Id {} failed to delete on {} for subnet {} : {}",
1068 vlanMulticastNextId, deviceId, vlanId, error)
1069 );
1070 flowObjectiveService.next(deviceId, l2MulticastGroupBuilder.remove(context));
1071
1072 // Finally clear store.
pier6c48dba2018-11-27 11:23:50 -08001073 removeMulticastGroup(key);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301074 }
1075
pier6c48dba2018-11-27 11:23:50 -08001076 private int getMulticastGroupNextObjectiveId(VlanNextObjectiveStoreKey key) {
1077 return Versioned.valueOrElse(xconnectMulticastNextStore.get(key), -1);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301078 }
1079
pier6c48dba2018-11-27 11:23:50 -08001080 private void addMulticastGroupNextObjectiveId(VlanNextObjectiveStoreKey key, int nextId) {
jayakumarthazhath46945b62018-10-01 00:51:54 +05301081 if (nextId == -1) {
1082 return;
1083 }
jayakumarthazhath46945b62018-10-01 00:51:54 +05301084 xconnectMulticastNextStore.put(key, nextId);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301085 }
1086
pier6c48dba2018-11-27 11:23:50 -08001087 private void addMulticastGroupPort(VlanNextObjectiveStoreKey groupKey, PortNumber port) {
1088 xconnectMulticastPortsStore.compute(groupKey, (key, ports) -> {
1089 if (ports == null) {
1090 ports = Lists.newArrayList();
1091 }
1092 ports.add(port);
1093 return ports;
1094 });
jayakumarthazhath46945b62018-10-01 00:51:54 +05301095 }
1096
pier6c48dba2018-11-27 11:23:50 -08001097 private void removeMulticastGroupPort(VlanNextObjectiveStoreKey groupKey, PortNumber port) {
1098 xconnectMulticastPortsStore.compute(groupKey, (key, ports) -> {
1099 if (ports != null && !ports.isEmpty()) {
1100 ports.remove(port);
1101 }
1102 return ports;
1103 });
jayakumarthazhath46945b62018-10-01 00:51:54 +05301104 }
1105
pier6c48dba2018-11-27 11:23:50 -08001106 private void removeMulticastGroup(VlanNextObjectiveStoreKey groupKey) {
1107 xconnectMulticastPortsStore.remove(groupKey);
1108 xconnectMulticastNextStore.remove(groupKey);
jayakumarthazhath46945b62018-10-01 00:51:54 +05301109 }
1110
pier6c48dba2018-11-27 11:23:50 -08001111 private boolean hasAccessPortInMulticastGroup(VlanNextObjectiveStoreKey groupKey, PortNumber pairPort) {
1112 List<PortNumber> ports = Versioned.valueOrElse(xconnectMulticastPortsStore.get(groupKey), ImmutableList.of());
jayakumarthazhath46945b62018-10-01 00:51:54 +05301113 return ports.stream().anyMatch(p -> !p.equals(pairPort));
1114 }
1115
pier6c48dba2018-11-27 11:23:50 -08001116 // Custom-built function, when the device is not available we need a fallback mechanism
1117 private boolean isLocalLeader(DeviceId deviceId) {
1118 if (!mastershipService.isLocalMaster(deviceId)) {
1119 // When the device is available we just check the mastership
1120 if (deviceService.isAvailable(deviceId)) {
1121 return false;
1122 }
1123 // Fallback with Leadership service - device id is used as topic
1124 NodeId leader = leadershipService.runForLeadership(
1125 deviceId.toString()).leaderNodeId();
1126 // Verify if this node is the leader
1127 return clusterService.getLocalNode().id().equals(leader);
1128 }
1129 return true;
1130 }
1131
Charles Chan4e87b3e2018-06-19 20:31:57 -07001132}