blob: 102d469be99f1d2dbe6b046bb40bcf13c2744859 [file] [log] [blame]
Charles Chan8d316332018-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
pier6fd24fd2018-11-27 11:23:50 -080018import com.google.common.collect.ImmutableList;
pier567465b2018-11-24 11:16:28 -080019import com.google.common.cache.Cache;
20import com.google.common.cache.CacheBuilder;
21import com.google.common.cache.RemovalNotification;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070022import com.google.common.collect.ImmutableMap;
Charles Chan8d316332018-06-19 20:31:57 -070023import com.google.common.collect.ImmutableSet;
pier6fd24fd2018-11-27 11:23:50 -080024import com.google.common.collect.Lists;
Charles Chan8d316332018-06-19 20:31:57 -070025import com.google.common.collect.Sets;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +053026import org.onlab.packet.Ethernet;
Charles Chan8d316332018-06-19 20:31:57 -070027import org.onlab.packet.MacAddress;
28import org.onlab.packet.VlanId;
29import org.onlab.util.KryoNamespace;
pier6fd24fd2018-11-27 11:23:50 -080030import org.onosproject.cluster.ClusterService;
31import org.onosproject.cluster.LeadershipService;
32import org.onosproject.cluster.NodeId;
Charles Chan8d316332018-06-19 20:31:57 -070033import org.onosproject.codec.CodecService;
34import org.onosproject.core.ApplicationId;
35import org.onosproject.core.CoreService;
Charles Chanc0a499b2019-01-16 15:30:39 -080036import org.onosproject.portloadbalancer.api.PortLoadBalancerEvent;
37import org.onosproject.portloadbalancer.api.PortLoadBalancerId;
38import org.onosproject.portloadbalancer.api.PortLoadBalancerListener;
39import org.onosproject.portloadbalancer.api.PortLoadBalancerService;
Charles Chan8d316332018-06-19 20:31:57 -070040import org.onosproject.mastership.MastershipService;
41import org.onosproject.net.ConnectPoint;
42import org.onosproject.net.DeviceId;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +053043import org.onosproject.net.Host;
44import org.onosproject.net.HostLocation;
Charles Chan8d316332018-06-19 20:31:57 -070045import org.onosproject.net.PortNumber;
46import org.onosproject.net.config.NetworkConfigService;
47import org.onosproject.net.device.DeviceEvent;
48import org.onosproject.net.device.DeviceListener;
49import org.onosproject.net.device.DeviceService;
50import org.onosproject.net.flow.DefaultTrafficSelector;
51import org.onosproject.net.flow.DefaultTrafficTreatment;
52import org.onosproject.net.flow.TrafficSelector;
53import org.onosproject.net.flow.TrafficTreatment;
54import org.onosproject.net.flow.criteria.Criteria;
55import org.onosproject.net.flowobjective.DefaultFilteringObjective;
56import org.onosproject.net.flowobjective.DefaultForwardingObjective;
57import org.onosproject.net.flowobjective.DefaultNextObjective;
Charles Chan48df9ad2018-10-30 18:08:59 -070058import org.onosproject.net.flowobjective.DefaultNextTreatment;
Charles Chan8d316332018-06-19 20:31:57 -070059import org.onosproject.net.flowobjective.DefaultObjectiveContext;
60import org.onosproject.net.flowobjective.FilteringObjective;
61import org.onosproject.net.flowobjective.FlowObjectiveService;
62import org.onosproject.net.flowobjective.ForwardingObjective;
Charles Chan48df9ad2018-10-30 18:08:59 -070063import org.onosproject.net.flowobjective.IdNextTreatment;
Charles Chan8d316332018-06-19 20:31:57 -070064import org.onosproject.net.flowobjective.NextObjective;
Charles Chan48df9ad2018-10-30 18:08:59 -070065import org.onosproject.net.flowobjective.NextTreatment;
Charles Chan8d316332018-06-19 20:31:57 -070066import org.onosproject.net.flowobjective.Objective;
67import org.onosproject.net.flowobjective.ObjectiveContext;
68import org.onosproject.net.flowobjective.ObjectiveError;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +053069import org.onosproject.net.host.HostEvent;
70import org.onosproject.net.host.HostListener;
71import org.onosproject.net.host.HostService;
72import org.onosproject.net.intf.InterfaceService;
Charles Chan8d316332018-06-19 20:31:57 -070073import org.onosproject.segmentrouting.SegmentRoutingService;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +053074import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -070075import org.onosproject.segmentrouting.xconnect.api.XconnectCodec;
76import org.onosproject.segmentrouting.xconnect.api.XconnectDesc;
Charles Chan445659f2019-01-02 13:46:16 -080077import org.onosproject.segmentrouting.xconnect.api.XconnectEndpoint;
Charles Chan8d316332018-06-19 20:31:57 -070078import org.onosproject.segmentrouting.xconnect.api.XconnectKey;
Charles Chan445659f2019-01-02 13:46:16 -080079import org.onosproject.segmentrouting.xconnect.api.XconnectLoadBalancerEndpoint;
80import org.onosproject.segmentrouting.xconnect.api.XconnectPortEndpoint;
Charles Chan8d316332018-06-19 20:31:57 -070081import org.onosproject.segmentrouting.xconnect.api.XconnectService;
82import org.onosproject.store.serializers.KryoNamespaces;
83import org.onosproject.store.service.ConsistentMap;
84import org.onosproject.store.service.MapEvent;
85import org.onosproject.store.service.MapEventListener;
86import org.onosproject.store.service.Serializer;
87import org.onosproject.store.service.StorageService;
88import org.onosproject.store.service.Versioned;
Ray Milkey2bd24a92018-08-17 14:54:17 -070089import org.osgi.service.component.annotations.Activate;
90import org.osgi.service.component.annotations.Component;
91import org.osgi.service.component.annotations.Deactivate;
92import org.osgi.service.component.annotations.Reference;
93import org.osgi.service.component.annotations.ReferenceCardinality;
Charles Chan8d316332018-06-19 20:31:57 -070094import org.slf4j.Logger;
95import org.slf4j.LoggerFactory;
96
97import java.io.Serializable;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +053098import java.util.Collections;
99import java.util.List;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530100import java.util.Optional;
Charles Chan8d316332018-06-19 20:31:57 -0700101import java.util.Set;
102import java.util.concurrent.CompletableFuture;
Charles Chan56542b62018-08-07 12:48:36 -0700103import java.util.concurrent.ExecutorService;
104import java.util.concurrent.Executors;
pier567465b2018-11-24 11:16:28 -0800105import java.util.concurrent.ScheduledExecutorService;
106import java.util.concurrent.TimeUnit;
Charles Chan8d316332018-06-19 20:31:57 -0700107import java.util.function.BiConsumer;
108import java.util.function.Consumer;
109import java.util.stream.Collectors;
110
pier567465b2018-11-24 11:16:28 -0800111import static java.util.concurrent.Executors.newScheduledThreadPool;
Charles Chan56542b62018-08-07 12:48:36 -0700112import static org.onlab.util.Tools.groupedThreads;
113
Ray Milkey2bd24a92018-08-17 14:54:17 -0700114@Component(immediate = true, service = XconnectService.class)
Charles Chan8d316332018-06-19 20:31:57 -0700115public class XconnectManager implements XconnectService {
Ray Milkey2bd24a92018-08-17 14:54:17 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700117 private CoreService coreService;
118
Ray Milkey2bd24a92018-08-17 14:54:17 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700120 private CodecService codecService;
121
Ray Milkey2bd24a92018-08-17 14:54:17 -0700122 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700123 private StorageService storageService;
124
Ray Milkey2bd24a92018-08-17 14:54:17 -0700125 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700126 public NetworkConfigService netCfgService;
127
Ray Milkey2bd24a92018-08-17 14:54:17 -0700128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700129 public DeviceService deviceService;
130
Ray Milkey2bd24a92018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700132 public FlowObjectiveService flowObjectiveService;
133
Ray Milkey2bd24a92018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pier6fd24fd2018-11-27 11:23:50 -0800135 private LeadershipService leadershipService;
136
137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
138 private ClusterService clusterService;
139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan8d316332018-06-19 20:31:57 -0700141 public MastershipService mastershipService;
142
Ray Milkey2bd24a92018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.OPTIONAL)
Charles Chan8d316332018-06-19 20:31:57 -0700144 public SegmentRoutingService srService;
145
Ray Milkey3cad4db2018-10-04 15:13:33 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530147 public InterfaceService interfaceService;
148
Ray Milkey3cad4db2018-10-04 15:13:33 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530150 HostService hostService;
151
Charles Chan48df9ad2018-10-30 18:08:59 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chanc0a499b2019-01-16 15:30:39 -0800153 private PortLoadBalancerService portLoadBalancerService;
Charles Chan48df9ad2018-10-30 18:08:59 -0700154
Charles Chan8d316332018-06-19 20:31:57 -0700155 private static final String APP_NAME = "org.onosproject.xconnect";
pier6fd24fd2018-11-27 11:23:50 -0800156 private static final String ERROR_NOT_LEADER = "Not leader controller";
Charles Chan48df9ad2018-10-30 18:08:59 -0700157 private static final String ERROR_NEXT_OBJ_BUILDER = "Unable to construct next objective builder";
158 private static final String ERROR_NEXT_ID = "Unable to get next id";
Charles Chan8d316332018-06-19 20:31:57 -0700159
160 private static Logger log = LoggerFactory.getLogger(XconnectManager.class);
161
162 private ApplicationId appId;
Charles Chan445659f2019-01-02 13:46:16 -0800163 private ConsistentMap<XconnectKey, Set<XconnectEndpoint>> xconnectStore;
Charles Chan1fb65132018-09-21 11:29:12 -0700164 private ConsistentMap<XconnectKey, Integer> xconnectNextObjStore;
Charles Chan8d316332018-06-19 20:31:57 -0700165
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530166 private ConsistentMap<VlanNextObjectiveStoreKey, Integer> xconnectMulticastNextStore;
167 private ConsistentMap<VlanNextObjectiveStoreKey, List<PortNumber>> xconnectMulticastPortsStore;
168
Charles Chan445659f2019-01-02 13:46:16 -0800169 private final MapEventListener<XconnectKey, Set<XconnectEndpoint>> xconnectListener = new XconnectMapListener();
pier6fd24fd2018-11-27 11:23:50 -0800170 private ExecutorService xConnectExecutor;
Charles Chan8d316332018-06-19 20:31:57 -0700171
pier6fd24fd2018-11-27 11:23:50 -0800172 private final DeviceListener deviceListener = new InternalDeviceListener();
Charles Chan56542b62018-08-07 12:48:36 -0700173 private ExecutorService deviceEventExecutor;
174
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530175 private final HostListener hostListener = new InternalHostListener();
176 private ExecutorService hostEventExecutor;
177
pier567465b2018-11-24 11:16:28 -0800178 // Wait time for the cache
179 private static final int WAIT_TIME_MS = 15000;
Charles Chanc0a499b2019-01-16 15:30:39 -0800180 //The cache is implemented as buffer for waiting the installation of PortLoadBalancer when present
181 private Cache<PortLoadBalancerId, XconnectKey> portLoadBalancerCache;
pier567465b2018-11-24 11:16:28 -0800182 // Executor for the cache
Charles Chanc0a499b2019-01-16 15:30:39 -0800183 private ScheduledExecutorService portLoadBalancerExecutor;
184 // We need to listen for some events to properly installed the xconnect with portloadbalancer
185 private final PortLoadBalancerListener portLoadBalancerListener = new InternalPortLoadBalancerListener();
pier567465b2018-11-24 11:16:28 -0800186
Charles Chan8d316332018-06-19 20:31:57 -0700187 @Activate
188 void activate() {
189 appId = coreService.registerApplication(APP_NAME);
190 codecService.registerCodec(XconnectDesc.class, new XconnectCodec());
191
192 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
193 .register(KryoNamespaces.API)
Charles Chanfbaad962018-07-23 12:53:16 -0700194 .register(XconnectManager.class)
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530195 .register(XconnectKey.class)
Charles Chan445659f2019-01-02 13:46:16 -0800196 .register(XconnectEndpoint.class)
197 .register(XconnectPortEndpoint.class)
198 .register(XconnectLoadBalancerEndpoint.class)
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530199 .register(VlanNextObjectiveStoreKey.class);
Charles Chan8d316332018-06-19 20:31:57 -0700200
Charles Chan445659f2019-01-02 13:46:16 -0800201 xconnectStore = storageService.<XconnectKey, Set<XconnectEndpoint>>consistentMapBuilder()
Charles Chan8d316332018-06-19 20:31:57 -0700202 .withName("onos-sr-xconnect")
203 .withRelaxedReadConsistency()
204 .withSerializer(Serializer.using(serializer.build()))
205 .build();
pier6fd24fd2018-11-27 11:23:50 -0800206 xConnectExecutor = Executors.newSingleThreadScheduledExecutor(
207 groupedThreads("sr-xconnect-event", "%d", log));
208 xconnectStore.addListener(xconnectListener, xConnectExecutor);
Charles Chan8d316332018-06-19 20:31:57 -0700209
Charles Chan1fb65132018-09-21 11:29:12 -0700210 xconnectNextObjStore = storageService.<XconnectKey, Integer>consistentMapBuilder()
Charles Chan8d316332018-06-19 20:31:57 -0700211 .withName("onos-sr-xconnect-next")
212 .withRelaxedReadConsistency()
213 .withSerializer(Serializer.using(serializer.build()))
214 .build();
215
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530216 xconnectMulticastNextStore = storageService.<VlanNextObjectiveStoreKey, Integer>consistentMapBuilder()
217 .withName("onos-sr-xconnect-l2multicast-next")
218 .withSerializer(Serializer.using(serializer.build()))
219 .build();
220 xconnectMulticastPortsStore = storageService.<VlanNextObjectiveStoreKey, List<PortNumber>>consistentMapBuilder()
221 .withName("onos-sr-xconnect-l2multicast-ports")
222 .withSerializer(Serializer.using(serializer.build()))
223 .build();
224
Charles Chan56542b62018-08-07 12:48:36 -0700225 deviceEventExecutor = Executors.newSingleThreadScheduledExecutor(
226 groupedThreads("sr-xconnect-device-event", "%d", log));
Charles Chan8d316332018-06-19 20:31:57 -0700227 deviceService.addListener(deviceListener);
228
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530229 hostEventExecutor = Executors.newSingleThreadExecutor(
230 groupedThreads("sr-xconnect-host-event", "%d", log));
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530231 hostService.addListener(hostListener);
232
Charles Chanc0a499b2019-01-16 15:30:39 -0800233 portLoadBalancerCache = CacheBuilder.newBuilder()
pier567465b2018-11-24 11:16:28 -0800234 .expireAfterWrite(WAIT_TIME_MS, TimeUnit.MILLISECONDS)
Charles Chanc0a499b2019-01-16 15:30:39 -0800235 .removalListener((RemovalNotification<PortLoadBalancerId, XconnectKey> notification) ->
236 log.debug("PortLoadBalancer cache removal event. portLoadBalancerId={}, xConnectKey={}",
pier567465b2018-11-24 11:16:28 -0800237 notification.getKey(), notification.getValue())).build();
Charles Chanc0a499b2019-01-16 15:30:39 -0800238 portLoadBalancerExecutor = newScheduledThreadPool(1,
239 groupedThreads("portLoadBalancerCacheWorker", "-%d", log));
pier567465b2018-11-24 11:16:28 -0800240 // Let's schedule the cleanup of the cache
Charles Chanc0a499b2019-01-16 15:30:39 -0800241 portLoadBalancerExecutor.scheduleAtFixedRate(portLoadBalancerCache::cleanUp, 0,
pier567465b2018-11-24 11:16:28 -0800242 WAIT_TIME_MS, TimeUnit.MILLISECONDS);
Charles Chanc0a499b2019-01-16 15:30:39 -0800243 portLoadBalancerService.addListener(portLoadBalancerListener);
pier567465b2018-11-24 11:16:28 -0800244
Charles Chan8d316332018-06-19 20:31:57 -0700245 log.info("Started");
246 }
247
248 @Deactivate
249 void deactivate() {
250 xconnectStore.removeListener(xconnectListener);
251 deviceService.removeListener(deviceListener);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530252 hostService.removeListener(hostListener);
pier98345be2019-04-01 23:38:42 -0700253 portLoadBalancerService.removeListener(portLoadBalancerListener);
Charles Chan8d316332018-06-19 20:31:57 -0700254 codecService.unregisterCodec(XconnectDesc.class);
255
Charles Chan56542b62018-08-07 12:48:36 -0700256 deviceEventExecutor.shutdown();
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530257 hostEventExecutor.shutdown();
pier6fd24fd2018-11-27 11:23:50 -0800258 xConnectExecutor.shutdown();
Charles Chanc0a499b2019-01-16 15:30:39 -0800259 portLoadBalancerExecutor.shutdown();
Charles Chan56542b62018-08-07 12:48:36 -0700260
Charles Chan8d316332018-06-19 20:31:57 -0700261 log.info("Stopped");
262 }
263
264 @Override
Charles Chan445659f2019-01-02 13:46:16 -0800265 public void addOrUpdateXconnect(DeviceId deviceId, VlanId vlanId, Set<XconnectEndpoint> endpoints) {
266 log.info("Adding or updating xconnect. deviceId={}, vlanId={}, endpoints={}",
267 deviceId, vlanId, endpoints);
Charles Chan8d316332018-06-19 20:31:57 -0700268 final XconnectKey key = new XconnectKey(deviceId, vlanId);
Charles Chan445659f2019-01-02 13:46:16 -0800269 xconnectStore.put(key, endpoints);
Charles Chan8d316332018-06-19 20:31:57 -0700270 }
271
272 @Override
273 public void removeXonnect(DeviceId deviceId, VlanId vlanId) {
274 log.info("Removing xconnect. deviceId={}, vlanId={}",
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530275 deviceId, vlanId);
Charles Chan8d316332018-06-19 20:31:57 -0700276 final XconnectKey key = new XconnectKey(deviceId, vlanId);
277 xconnectStore.remove(key);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530278
279 // Cleanup multicasting support, if any.
Charles Chan445659f2019-01-02 13:46:16 -0800280 srService.getPairDeviceId(deviceId).ifPresent(pairDeviceId ->
281 cleanupL2MulticastRule(pairDeviceId, srService.getPairLocalPort(pairDeviceId).get(), vlanId, true)
282 );
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530283
Charles Chan8d316332018-06-19 20:31:57 -0700284 }
285
286 @Override
287 public Set<XconnectDesc> getXconnects() {
288 return xconnectStore.asJavaMap().entrySet().stream()
289 .map(e -> new XconnectDesc(e.getKey(), e.getValue()))
290 .collect(Collectors.toSet());
291 }
292
293 @Override
294 public boolean hasXconnect(ConnectPoint cp) {
Charles Chan445659f2019-01-02 13:46:16 -0800295 return getXconnects().stream().anyMatch(desc ->
296 desc.key().deviceId().equals(cp.deviceId()) && desc.endpoints().stream().anyMatch(ep ->
297 ep.type() == XconnectEndpoint.Type.PORT && ((XconnectPortEndpoint) ep).port().equals(cp.port())
298 )
Charles Chan8d316332018-06-19 20:31:57 -0700299 );
300 }
301
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700302 @Override
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530303 public List<VlanId> getXconnectVlans(DeviceId deviceId, PortNumber port) {
304 return getXconnects().stream()
Charles Chan445659f2019-01-02 13:46:16 -0800305 .filter(desc -> desc.key().deviceId().equals(deviceId) && desc.endpoints().stream().anyMatch(ep ->
306 ep.type() == XconnectEndpoint.Type.PORT && ((XconnectPortEndpoint) ep).port().equals(port)))
307 .map(XconnectDesc::key)
308 .map(XconnectKey::vlanId)
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530309 .collect(Collectors.toList());
310 }
311
312 @Override
313 public boolean isXconnectVlan(DeviceId deviceId, VlanId vlanId) {
pier6fd24fd2018-11-27 11:23:50 -0800314 XconnectKey key = new XconnectKey(deviceId, vlanId);
315 return Versioned.valueOrNull(xconnectStore.get(key)) != null;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530316 }
317
318 @Override
Charles Chan1fb65132018-09-21 11:29:12 -0700319 public ImmutableMap<XconnectKey, Integer> getNext() {
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700320 if (xconnectNextObjStore != null) {
321 return ImmutableMap.copyOf(xconnectNextObjStore.asJavaMap());
322 } else {
323 return ImmutableMap.of();
324 }
325 }
326
327 @Override
pier6fd24fd2018-11-27 11:23:50 -0800328 public int getNextId(DeviceId deviceId, VlanId vlanId) {
329 return Versioned.valueOrElse(xconnectNextObjStore.get(new XconnectKey(deviceId, vlanId)), -1);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530330 }
331
332 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700333 public void removeNextId(int nextId) {
334 xconnectNextObjStore.entrySet().forEach(e -> {
Charles Chan1fb65132018-09-21 11:29:12 -0700335 if (e.getValue().value() == nextId) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700336 xconnectNextObjStore.remove(e.getKey());
337 }
338 });
339 }
340
Charles Chan445659f2019-01-02 13:46:16 -0800341 private class XconnectMapListener implements MapEventListener<XconnectKey, Set<XconnectEndpoint>> {
Charles Chan8d316332018-06-19 20:31:57 -0700342 @Override
Charles Chan445659f2019-01-02 13:46:16 -0800343 public void event(MapEvent<XconnectKey, Set<XconnectEndpoint>> event) {
Charles Chan8d316332018-06-19 20:31:57 -0700344 XconnectKey key = event.key();
Charles Chan445659f2019-01-02 13:46:16 -0800345 Set<XconnectEndpoint> ports = Versioned.valueOrNull(event.newValue());
346 Set<XconnectEndpoint> oldPorts = Versioned.valueOrNull(event.oldValue());
Charles Chan8d316332018-06-19 20:31:57 -0700347
348 switch (event.type()) {
349 case INSERT:
Charles Chan48df9ad2018-10-30 18:08:59 -0700350 populateXConnect(key, ports);
Charles Chan8d316332018-06-19 20:31:57 -0700351 break;
352 case UPDATE:
Charles Chan48df9ad2018-10-30 18:08:59 -0700353 updateXConnect(key, oldPorts, ports);
Charles Chan8d316332018-06-19 20:31:57 -0700354 break;
355 case REMOVE:
Charles Chan48df9ad2018-10-30 18:08:59 -0700356 revokeXConnect(key, oldPorts);
Charles Chan8d316332018-06-19 20:31:57 -0700357 break;
358 default:
359 break;
360 }
361 }
362 }
363
364 private class InternalDeviceListener implements DeviceListener {
pier6fd24fd2018-11-27 11:23:50 -0800365 // Offload the execution to an executor and then process the event
366 // if this instance is the leader of the device
Charles Chan8d316332018-06-19 20:31:57 -0700367 @Override
368 public void event(DeviceEvent event) {
Charles Chan56542b62018-08-07 12:48:36 -0700369 deviceEventExecutor.execute(() -> {
370 DeviceId deviceId = event.subject().id();
pier6fd24fd2018-11-27 11:23:50 -0800371 // Just skip if we are not the leader
372 if (!isLocalLeader(deviceId)) {
373 log.debug("Not the leader of {}. Skip event {}", deviceId, event);
Charles Chan56542b62018-08-07 12:48:36 -0700374 return;
375 }
pier6fd24fd2018-11-27 11:23:50 -0800376 // Populate or revoke according to the device availability
377 if (deviceService.isAvailable(deviceId)) {
378 init(deviceId);
379 } else {
380 cleanup(deviceId);
Charles Chan56542b62018-08-07 12:48:36 -0700381 }
382 });
Charles Chan8d316332018-06-19 20:31:57 -0700383 }
pier6fd24fd2018-11-27 11:23:50 -0800384 // We want to manage only a subset of events and if we are the leader
385 @Override
386 public boolean isRelevant(DeviceEvent event) {
387 return event.type() == DeviceEvent.Type.DEVICE_ADDED ||
388 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
389 event.type() == DeviceEvent.Type.DEVICE_UPDATED;
390 }
Charles Chan8d316332018-06-19 20:31:57 -0700391 }
392
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530393 private class InternalHostListener implements HostListener {
394 @Override
395 public void event(HostEvent event) {
396 hostEventExecutor.execute(() -> {
397
398 switch (event.type()) {
399 case HOST_MOVED:
400 log.trace("Processing host event {}", event);
401
402 Host host = event.subject();
403 Set<HostLocation> prevLocations = event.prevSubject().locations();
404 Set<HostLocation> newLocations = host.locations();
405
406 // Dual-home host port failure
407 // For each old location, in failed and paired devices update L2 vlan groups
408 Sets.difference(prevLocations, newLocations).forEach(prevLocation -> {
409
410 Optional<DeviceId> pairDeviceId = srService.getPairDeviceId(prevLocation.deviceId());
411 Optional<PortNumber> pairLocalPort = srService.getPairLocalPort(prevLocation.deviceId());
412
413 if (pairDeviceId.isPresent() && pairLocalPort.isPresent() && newLocations.stream()
414 .anyMatch(location -> location.deviceId().equals(pairDeviceId.get())) &&
415 hasXconnect(new ConnectPoint(prevLocation.deviceId(), prevLocation.port()))) {
416
417 List<VlanId> xconnectVlans = getXconnectVlans(prevLocation.deviceId(),
418 prevLocation.port());
419 xconnectVlans.forEach(xconnectVlan -> {
420 // Add single-home host into L2 multicast group at paired device side.
421 // Also append ACL rule to forward traffic from paired port to L2 multicast group.
422 newLocations.stream()
423 .filter(location -> location.deviceId().equals(pairDeviceId.get()))
424 .forEach(location -> populateL2Multicast(location.deviceId(),
425 srService.getPairLocalPort(
426 location.deviceId()).get(),
427 xconnectVlan,
428 Collections.singletonList(
429 location.port())));
pier6fd24fd2018-11-27 11:23:50 -0800430 // Ensure pair-port attached to xconnect vlan flooding group
431 // at dual home failed device.
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530432 updateL2Flooding(prevLocation.deviceId(), pairLocalPort.get(), xconnectVlan, true);
433 });
434 }
435 });
436
437 // Dual-home host port restoration
438 // For each new location, reverse xconnect loop prevention groups.
439 Sets.difference(newLocations, prevLocations).forEach(newLocation -> {
440 final Optional<DeviceId> pairDeviceId = srService.getPairDeviceId(newLocation.deviceId());
441 Optional<PortNumber> pairLocalPort = srService.getPairLocalPort(newLocation.deviceId());
442 if (pairDeviceId.isPresent() && pairLocalPort.isPresent() &&
443 hasXconnect((new ConnectPoint(newLocation.deviceId(), newLocation.port())))) {
444
445 List<VlanId> xconnectVlans = getXconnectVlans(newLocation.deviceId(),
446 newLocation.port());
447 xconnectVlans.forEach(xconnectVlan -> {
448 // Remove recovered dual homed port from vlan L2 multicast group
449 prevLocations.stream()
450 .filter(prevLocation -> prevLocation.deviceId().equals(pairDeviceId.get()))
pier6fd24fd2018-11-27 11:23:50 -0800451 .forEach(prevLocation -> revokeL2Multicast(
452 prevLocation.deviceId(),
453 xconnectVlan,
454 Collections.singletonList(newLocation.port()))
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530455 );
456
pier6fd24fd2018-11-27 11:23:50 -0800457 // Remove pair-port from vlan's flooding group at dual home
458 // restored device, if needed.
459 if (!hasAccessPortInMulticastGroup(new VlanNextObjectiveStoreKey(
460 newLocation.deviceId(), xconnectVlan), pairLocalPort.get())) {
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530461 updateL2Flooding(newLocation.deviceId(),
462 pairLocalPort.get(),
463 xconnectVlan,
464 false);
465
466 // Clean L2 multicast group at pair-device; also update store.
467 cleanupL2MulticastRule(pairDeviceId.get(),
468 srService.getPairLocalPort(pairDeviceId.get()).get(),
469 xconnectVlan,
470 false);
471 }
472 });
473 }
474 });
475 break;
476
477 default:
478 log.warn("Unsupported host event type: {} received. Ignoring.", event.type());
479 break;
480 }
481 });
482 }
483 }
484
Charles Chan1fb65132018-09-21 11:29:12 -0700485 private void init(DeviceId deviceId) {
Charles Chan8d316332018-06-19 20:31:57 -0700486 getXconnects().stream()
487 .filter(desc -> desc.key().deviceId().equals(deviceId))
Charles Chan445659f2019-01-02 13:46:16 -0800488 .forEach(desc -> populateXConnect(desc.key(), desc.endpoints()));
Charles Chan8d316332018-06-19 20:31:57 -0700489 }
490
Charles Chan1fb65132018-09-21 11:29:12 -0700491 private void cleanup(DeviceId deviceId) {
Charles Chan8d316332018-06-19 20:31:57 -0700492 xconnectNextObjStore.entrySet().stream()
493 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
494 .forEach(entry -> xconnectNextObjStore.remove(entry.getKey()));
495 log.debug("{} is removed from xConnectNextObjStore", deviceId);
496 }
497
498 /**
499 * Populates XConnect groups and flows for given key.
500 *
Charles Chan445659f2019-01-02 13:46:16 -0800501 * @param key XConnect key
502 * @param endpoints a set of endpoints to be cross-connected
Charles Chan8d316332018-06-19 20:31:57 -0700503 */
Charles Chan445659f2019-01-02 13:46:16 -0800504 private void populateXConnect(XconnectKey key, Set<XconnectEndpoint> endpoints) {
pier6fd24fd2018-11-27 11:23:50 -0800505 if (!isLocalLeader(key.deviceId())) {
506 log.debug("Abort populating XConnect {}: {}", key, ERROR_NOT_LEADER);
Charles Chan8d316332018-06-19 20:31:57 -0700507 return;
508 }
509
Charles Chan445659f2019-01-02 13:46:16 -0800510 int nextId = populateNext(key, endpoints);
Charles Chan48df9ad2018-10-30 18:08:59 -0700511 if (nextId == -1) {
512 log.warn("Fail to populateXConnect {}: {}", key, ERROR_NEXT_ID);
513 return;
514 }
Charles Chan445659f2019-01-02 13:46:16 -0800515 populateFilter(key, endpoints);
Charles Chan48df9ad2018-10-30 18:08:59 -0700516 populateFwd(key, nextId);
Charles Chan8d316332018-06-19 20:31:57 -0700517 populateAcl(key);
518 }
519
520 /**
521 * Populates filtering objectives for given XConnect.
522 *
Charles Chan445659f2019-01-02 13:46:16 -0800523 * @param key XConnect store key
524 * @param endpoints XConnect endpoints
Charles Chan8d316332018-06-19 20:31:57 -0700525 */
Charles Chan445659f2019-01-02 13:46:16 -0800526 private void populateFilter(XconnectKey key, Set<XconnectEndpoint> endpoints) {
Charles Chan48df9ad2018-10-30 18:08:59 -0700527 // FIXME Improve the logic
Charles Chanc0a499b2019-01-16 15:30:39 -0800528 // If port load balancer is not involved, use filtered port. Otherwise, use unfiltered port.
Charles Chan48df9ad2018-10-30 18:08:59 -0700529 // The purpose is to make sure existing XConnect logic can still work on a configured port.
Charles Chan445659f2019-01-02 13:46:16 -0800530 boolean filtered = endpoints.stream()
531 .map(ep -> getNextTreatment(key.deviceId(), ep, false))
Charles Chan48df9ad2018-10-30 18:08:59 -0700532 .allMatch(t -> t.type().equals(NextTreatment.Type.TREATMENT));
533
Charles Chan445659f2019-01-02 13:46:16 -0800534 endpoints.stream()
535 .map(ep -> getPhysicalPorts(key.deviceId(), ep))
Charles Chan48df9ad2018-10-30 18:08:59 -0700536 .flatMap(Set::stream).forEach(port -> {
Charles Chan445659f2019-01-02 13:46:16 -0800537 FilteringObjective.Builder filtObjBuilder = filterObjBuilder(key, port, filtered);
538 ObjectiveContext context = new DefaultObjectiveContext(
539 (objective) -> log.debug("XConnect FilterObj for {} on port {} populated",
540 key, port),
541 (objective, error) ->
542 log.warn("Failed to populate XConnect FilterObj for {} on port {}: {}",
543 key, port, error));
544 flowObjectiveService.filter(key.deviceId(), filtObjBuilder.add(context));
545 });
Charles Chan8d316332018-06-19 20:31:57 -0700546 }
547
548 /**
549 * Populates next objectives for given XConnect.
550 *
Charles Chan445659f2019-01-02 13:46:16 -0800551 * @param key XConnect store key
552 * @param endpoints XConnect endpoints
Charles Chan48df9ad2018-10-30 18:08:59 -0700553 * @return next id
Charles Chan8d316332018-06-19 20:31:57 -0700554 */
Charles Chan445659f2019-01-02 13:46:16 -0800555 private int populateNext(XconnectKey key, Set<XconnectEndpoint> endpoints) {
pier6fd24fd2018-11-27 11:23:50 -0800556 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
557 if (nextId != -1) {
Charles Chan1fb65132018-09-21 11:29:12 -0700558 log.debug("NextObj for {} found, id={}", key, nextId);
559 return nextId;
Charles Chan8d316332018-06-19 20:31:57 -0700560 } else {
Charles Chan445659f2019-01-02 13:46:16 -0800561 NextObjective.Builder nextObjBuilder = nextObjBuilder(key, endpoints);
Charles Chan48df9ad2018-10-30 18:08:59 -0700562 if (nextObjBuilder == null) {
563 log.warn("Fail to populate {}: {}", key, ERROR_NEXT_OBJ_BUILDER);
564 return -1;
565 }
Charles Chan8d316332018-06-19 20:31:57 -0700566 ObjectiveContext nextContext = new DefaultObjectiveContext(
567 // To serialize this with kryo
568 (Serializable & Consumer<Objective>) (objective) ->
569 log.debug("XConnect NextObj for {} added", key),
Charles Chanfacfbef2018-08-23 14:30:33 -0700570 (Serializable & BiConsumer<Objective, ObjectiveError>) (objective, error) -> {
571 log.warn("Failed to add XConnect NextObj for {}: {}", key, error);
572 srService.invalidateNextObj(objective.id());
573 });
Charles Chan1fb65132018-09-21 11:29:12 -0700574 NextObjective nextObj = nextObjBuilder.add(nextContext);
Charles Chan8d316332018-06-19 20:31:57 -0700575 flowObjectiveService.next(key.deviceId(), nextObj);
Charles Chan1fb65132018-09-21 11:29:12 -0700576 xconnectNextObjStore.put(key, nextObj.id());
Charles Chan8d316332018-06-19 20:31:57 -0700577 log.debug("NextObj for {} not found. Creating new NextObj with id={}", key, nextObj.id());
Charles Chan1fb65132018-09-21 11:29:12 -0700578 return nextObj.id();
Charles Chan8d316332018-06-19 20:31:57 -0700579 }
Charles Chan8d316332018-06-19 20:31:57 -0700580 }
581
582 /**
583 * Populates bridging forwarding objectives for given XConnect.
584 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530585 * @param key XConnect store key
Charles Chan1fb65132018-09-21 11:29:12 -0700586 * @param nextId next objective id
Charles Chan8d316332018-06-19 20:31:57 -0700587 */
Charles Chan1fb65132018-09-21 11:29:12 -0700588 private void populateFwd(XconnectKey key, int nextId) {
589 ForwardingObjective.Builder fwdObjBuilder = fwdObjBuilder(key, nextId);
Charles Chan8d316332018-06-19 20:31:57 -0700590 ObjectiveContext fwdContext = new DefaultObjectiveContext(
591 (objective) -> log.debug("XConnect FwdObj for {} populated", key),
592 (objective, error) ->
593 log.warn("Failed to populate XConnect FwdObj for {}: {}", key, error));
594 flowObjectiveService.forward(key.deviceId(), fwdObjBuilder.add(fwdContext));
595 }
596
597 /**
598 * Populates ACL forwarding objectives for given XConnect.
599 *
600 * @param key XConnect store key
601 */
602 private void populateAcl(XconnectKey key) {
603 ForwardingObjective.Builder aclObjBuilder = aclObjBuilder(key.vlanId());
604 ObjectiveContext aclContext = new DefaultObjectiveContext(
605 (objective) -> log.debug("XConnect AclObj for {} populated", key),
606 (objective, error) ->
607 log.warn("Failed to populate XConnect AclObj for {}: {}", key, error));
608 flowObjectiveService.forward(key.deviceId(), aclObjBuilder.add(aclContext));
609 }
610
611 /**
612 * Revokes XConnect groups and flows for given key.
613 *
Charles Chan445659f2019-01-02 13:46:16 -0800614 * @param key XConnect key
615 * @param endpoints XConnect endpoints
Charles Chan8d316332018-06-19 20:31:57 -0700616 */
Charles Chan445659f2019-01-02 13:46:16 -0800617 private void revokeXConnect(XconnectKey key, Set<XconnectEndpoint> endpoints) {
pier6fd24fd2018-11-27 11:23:50 -0800618 if (!isLocalLeader(key.deviceId())) {
619 log.debug("Abort revoking XConnect {}: {}", key, ERROR_NOT_LEADER);
Charles Chan8d316332018-06-19 20:31:57 -0700620 return;
621 }
622
Charles Chan445659f2019-01-02 13:46:16 -0800623 revokeFilter(key, endpoints);
pier6fd24fd2018-11-27 11:23:50 -0800624 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
625 if (nextId != -1) {
Charles Chan1fb65132018-09-21 11:29:12 -0700626 revokeFwd(key, nextId, null);
Charles Chan445659f2019-01-02 13:46:16 -0800627 revokeNext(key, endpoints, nextId, null);
Charles Chan8d316332018-06-19 20:31:57 -0700628 } else {
629 log.warn("NextObj for {} does not exist in the store.", key);
630 }
Charles Chan445659f2019-01-02 13:46:16 -0800631 revokeFilter(key, endpoints);
Charles Chan8d316332018-06-19 20:31:57 -0700632 revokeAcl(key);
633 }
634
635 /**
636 * Revokes filtering objectives for given XConnect.
637 *
Charles Chan445659f2019-01-02 13:46:16 -0800638 * @param key XConnect store key
639 * @param endpoints XConnect endpoints
Charles Chan8d316332018-06-19 20:31:57 -0700640 */
Charles Chan445659f2019-01-02 13:46:16 -0800641 private void revokeFilter(XconnectKey key, Set<XconnectEndpoint> endpoints) {
Charles Chan48df9ad2018-10-30 18:08:59 -0700642 // FIXME Improve the logic
Charles Chanc0a499b2019-01-16 15:30:39 -0800643 // If port load balancer is not involved, use filtered port. Otherwise, use unfiltered port.
Charles Chan48df9ad2018-10-30 18:08:59 -0700644 // The purpose is to make sure existing XConnect logic can still work on a configured port.
Charles Chan445659f2019-01-02 13:46:16 -0800645 boolean filtered = endpoints.stream()
646 .map(ep -> getNextTreatment(key.deviceId(), ep, false))
647 .allMatch(t -> t.type().equals(NextTreatment.Type.TREATMENT));
648
649 endpoints.stream()
650 .map(ep -> getPhysicalPorts(key.deviceId(), ep)).
651 flatMap(Set::stream).forEach(port -> {
652 FilteringObjective.Builder filtObjBuilder = filterObjBuilder(key, port, filtered);
653 ObjectiveContext context = new DefaultObjectiveContext(
654 (objective) -> log.debug("XConnect FilterObj for {} on port {} revoked",
655 key, port),
656 (objective, error) ->
657 log.warn("Failed to revoke XConnect FilterObj for {} on port {}: {}",
658 key, port, error));
659 flowObjectiveService.filter(key.deviceId(), filtObjBuilder.remove(context));
660 });
Charles Chan8d316332018-06-19 20:31:57 -0700661 }
662
663 /**
664 * Revokes next objectives for given XConnect.
665 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530666 * @param key XConnect store key
Charles Chan445659f2019-01-02 13:46:16 -0800667 * @param endpoints XConnect endpoints
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530668 * @param nextId next objective id
Charles Chan8d316332018-06-19 20:31:57 -0700669 * @param nextFuture completable future for this next objective operation
670 */
Charles Chan445659f2019-01-02 13:46:16 -0800671 private void revokeNext(XconnectKey key, Set<XconnectEndpoint> endpoints, int nextId,
Charles Chan8d316332018-06-19 20:31:57 -0700672 CompletableFuture<ObjectiveError> nextFuture) {
673 ObjectiveContext context = new ObjectiveContext() {
674 @Override
675 public void onSuccess(Objective objective) {
676 log.debug("Previous NextObj for {} removed", key);
677 if (nextFuture != null) {
678 nextFuture.complete(null);
679 }
680 }
681
682 @Override
683 public void onError(Objective objective, ObjectiveError error) {
684 log.warn("Failed to remove previous NextObj for {}: {}", key, error);
685 if (nextFuture != null) {
686 nextFuture.complete(error);
687 }
Charles Chanfacfbef2018-08-23 14:30:33 -0700688 srService.invalidateNextObj(objective.id());
Charles Chan8d316332018-06-19 20:31:57 -0700689 }
690 };
Charles Chan48df9ad2018-10-30 18:08:59 -0700691
Charles Chan445659f2019-01-02 13:46:16 -0800692 NextObjective.Builder nextObjBuilder = nextObjBuilder(key, endpoints, nextId);
Charles Chan48df9ad2018-10-30 18:08:59 -0700693 if (nextObjBuilder == null) {
694 log.warn("Fail to revokeNext {}: {}", key, ERROR_NEXT_OBJ_BUILDER);
695 return;
696 }
Charles Chanc0a499b2019-01-16 15:30:39 -0800697 // Release the port load balancer if present
Charles Chan445659f2019-01-02 13:46:16 -0800698 endpoints.stream()
699 .filter(endpoint -> endpoint.type() == XconnectEndpoint.Type.LOAD_BALANCER)
700 .forEach(endpoint -> {
Charles Chanc0a499b2019-01-16 15:30:39 -0800701 String portLoadBalancerKey = String.valueOf(((XconnectLoadBalancerEndpoint) endpoint).key());
702 portLoadBalancerService.release(new PortLoadBalancerId(key.deviceId(),
703 Integer.parseInt(portLoadBalancerKey)), appId);
Charles Chan445659f2019-01-02 13:46:16 -0800704 });
Charles Chan48df9ad2018-10-30 18:08:59 -0700705 flowObjectiveService.next(key.deviceId(), nextObjBuilder.remove(context));
Charles Chan8d316332018-06-19 20:31:57 -0700706 xconnectNextObjStore.remove(key);
707 }
708
709 /**
710 * Revokes bridging forwarding objectives for given XConnect.
711 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530712 * @param key XConnect store key
713 * @param nextId next objective id
Charles Chan8d316332018-06-19 20:31:57 -0700714 * @param fwdFuture completable future for this forwarding objective operation
715 */
Charles Chan1fb65132018-09-21 11:29:12 -0700716 private void revokeFwd(XconnectKey key, int nextId, CompletableFuture<ObjectiveError> fwdFuture) {
717 ForwardingObjective.Builder fwdObjBuilder = fwdObjBuilder(key, nextId);
Charles Chan8d316332018-06-19 20:31:57 -0700718 ObjectiveContext context = new ObjectiveContext() {
719 @Override
720 public void onSuccess(Objective objective) {
721 log.debug("Previous FwdObj for {} removed", key);
722 if (fwdFuture != null) {
723 fwdFuture.complete(null);
724 }
725 }
726
727 @Override
728 public void onError(Objective objective, ObjectiveError error) {
729 log.warn("Failed to remove previous FwdObj for {}: {}", key, error);
730 if (fwdFuture != null) {
731 fwdFuture.complete(error);
732 }
733 }
734 };
735 flowObjectiveService.forward(key.deviceId(), fwdObjBuilder.remove(context));
736 }
737
738 /**
739 * Revokes ACL forwarding objectives for given XConnect.
740 *
741 * @param key XConnect store key
742 */
743 private void revokeAcl(XconnectKey key) {
744 ForwardingObjective.Builder aclObjBuilder = aclObjBuilder(key.vlanId());
745 ObjectiveContext aclContext = new DefaultObjectiveContext(
746 (objective) -> log.debug("XConnect AclObj for {} populated", key),
747 (objective, error) ->
748 log.warn("Failed to populate XConnect AclObj for {}: {}", key, error));
749 flowObjectiveService.forward(key.deviceId(), aclObjBuilder.remove(aclContext));
750 }
751
752 /**
753 * Updates XConnect groups and flows for given key.
754 *
Charles Chan445659f2019-01-02 13:46:16 -0800755 * @param key XConnect key
756 * @param prevEndpoints previous XConnect endpoints
757 * @param endpoints new XConnect endpoints
Charles Chan8d316332018-06-19 20:31:57 -0700758 */
Charles Chan445659f2019-01-02 13:46:16 -0800759 private void updateXConnect(XconnectKey key, Set<XconnectEndpoint> prevEndpoints,
760 Set<XconnectEndpoint> endpoints) {
pier6fd24fd2018-11-27 11:23:50 -0800761 if (!isLocalLeader(key.deviceId())) {
762 log.debug("Abort updating XConnect {}: {}", key, ERROR_NOT_LEADER);
763 return;
764 }
Charles Chan8d316332018-06-19 20:31:57 -0700765 // NOTE: ACL flow doesn't include port information. No need to update it.
766 // Pair port is built-in and thus not going to change. No need to update it.
767
768 // remove old filter
Charles Chan445659f2019-01-02 13:46:16 -0800769 prevEndpoints.stream().filter(prevEndpoint -> !endpoints.contains(prevEndpoint)).forEach(prevEndpoint ->
770 revokeFilter(key, ImmutableSet.of(prevEndpoint)));
Charles Chan8d316332018-06-19 20:31:57 -0700771 // install new filter
Charles Chan445659f2019-01-02 13:46:16 -0800772 endpoints.stream().filter(endpoint -> !prevEndpoints.contains(endpoint)).forEach(endpoint ->
773 populateFilter(key, ImmutableSet.of(endpoint)));
Charles Chan8d316332018-06-19 20:31:57 -0700774
775 CompletableFuture<ObjectiveError> fwdFuture = new CompletableFuture<>();
776 CompletableFuture<ObjectiveError> nextFuture = new CompletableFuture<>();
777
pier6fd24fd2018-11-27 11:23:50 -0800778 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
779 if (nextId != -1) {
Charles Chan1fb65132018-09-21 11:29:12 -0700780 revokeFwd(key, nextId, fwdFuture);
Charles Chan8d316332018-06-19 20:31:57 -0700781
782 fwdFuture.thenAcceptAsync(fwdStatus -> {
783 if (fwdStatus == null) {
784 log.debug("Fwd removed. Now remove group {}", key);
Charles Chan445659f2019-01-02 13:46:16 -0800785 revokeNext(key, prevEndpoints, nextId, nextFuture);
Charles Chan8d316332018-06-19 20:31:57 -0700786 }
787 });
788
789 nextFuture.thenAcceptAsync(nextStatus -> {
790 if (nextStatus == null) {
791 log.debug("Installing new group and flow for {}", key);
Charles Chan445659f2019-01-02 13:46:16 -0800792 int newNextId = populateNext(key, endpoints);
Charles Chan48df9ad2018-10-30 18:08:59 -0700793 if (newNextId == -1) {
794 log.warn("Fail to updateXConnect {}: {}", key, ERROR_NEXT_ID);
795 return;
796 }
797 populateFwd(key, newNextId);
Charles Chan8d316332018-06-19 20:31:57 -0700798 }
799 });
800 } else {
801 log.warn("NextObj for {} does not exist in the store.", key);
802 }
803 }
804
805 /**
Charles Chan1fb65132018-09-21 11:29:12 -0700806 * Creates a next objective builder for XConnect with given nextId.
Charles Chan8d316332018-06-19 20:31:57 -0700807 *
Charles Chan445659f2019-01-02 13:46:16 -0800808 * @param key XConnect key
809 * @param endpoints XConnect endpoints
Charles Chan48df9ad2018-10-30 18:08:59 -0700810 * @param nextId next objective id
Charles Chan8d316332018-06-19 20:31:57 -0700811 * @return next objective builder
812 */
Charles Chan445659f2019-01-02 13:46:16 -0800813 private NextObjective.Builder nextObjBuilder(XconnectKey key, Set<XconnectEndpoint> endpoints, int nextId) {
Charles Chan8d316332018-06-19 20:31:57 -0700814 TrafficSelector metadata =
815 DefaultTrafficSelector.builder().matchVlanId(key.vlanId()).build();
816 NextObjective.Builder nextObjBuilder = DefaultNextObjective
817 .builder().withId(nextId)
818 .withType(NextObjective.Type.BROADCAST).fromApp(appId)
819 .withMeta(metadata);
Charles Chan48df9ad2018-10-30 18:08:59 -0700820
Charles Chan445659f2019-01-02 13:46:16 -0800821 for (XconnectEndpoint endpoint : endpoints) {
822 NextTreatment nextTreatment = getNextTreatment(key.deviceId(), endpoint, true);
Charles Chan48df9ad2018-10-30 18:08:59 -0700823 if (nextTreatment == null) {
Charles Chanc0a499b2019-01-16 15:30:39 -0800824 // If a PortLoadBalancer is used in the XConnect - putting on hold
Charles Chan445659f2019-01-02 13:46:16 -0800825 if (endpoint.type() == XconnectEndpoint.Type.LOAD_BALANCER) {
Charles Chanc0a499b2019-01-16 15:30:39 -0800826 log.warn("Unable to create nextObj. PortLoadBalancer not ready");
827 String portLoadBalancerKey = String.valueOf(((XconnectLoadBalancerEndpoint) endpoint).key());
828 portLoadBalancerCache.asMap().putIfAbsent(new PortLoadBalancerId(key.deviceId(),
829 Integer.parseInt(portLoadBalancerKey)), key);
pier567465b2018-11-24 11:16:28 -0800830 } else {
831 log.warn("Unable to create nextObj. Null NextTreatment");
832 }
Charles Chan48df9ad2018-10-30 18:08:59 -0700833 return null;
834 }
835 nextObjBuilder.addTreatment(nextTreatment);
836 }
837
Charles Chan8d316332018-06-19 20:31:57 -0700838 return nextObjBuilder;
839 }
840
841 /**
Charles Chan1fb65132018-09-21 11:29:12 -0700842 * Creates a next objective builder for XConnect.
843 *
Charles Chan445659f2019-01-02 13:46:16 -0800844 * @param key XConnect key
845 * @param endpoints Xconnect endpoints
Charles Chan1fb65132018-09-21 11:29:12 -0700846 * @return next objective builder
847 */
Charles Chan445659f2019-01-02 13:46:16 -0800848 private NextObjective.Builder nextObjBuilder(XconnectKey key, Set<XconnectEndpoint> endpoints) {
Charles Chan1fb65132018-09-21 11:29:12 -0700849 int nextId = flowObjectiveService.allocateNextId();
Charles Chan445659f2019-01-02 13:46:16 -0800850 return nextObjBuilder(key, endpoints, nextId);
Charles Chan1fb65132018-09-21 11:29:12 -0700851 }
852
853
854 /**
Charles Chan8d316332018-06-19 20:31:57 -0700855 * Creates a bridging forwarding objective builder for XConnect.
856 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530857 * @param key XConnect key
Charles Chan8d316332018-06-19 20:31:57 -0700858 * @param nextId next ID of the broadcast group for this XConnect key
859 * @return forwarding objective builder
860 */
861 private ForwardingObjective.Builder fwdObjBuilder(XconnectKey key, int nextId) {
862 /*
863 * Driver should treat objectives with MacAddress.NONE and !VlanId.NONE
864 * as the VLAN cross-connect broadcast rules
865 */
866 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
867 sbuilder.matchVlanId(key.vlanId());
868 sbuilder.matchEthDst(MacAddress.NONE);
869
870 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
871 fob.withFlag(ForwardingObjective.Flag.SPECIFIC)
872 .withSelector(sbuilder.build())
873 .nextStep(nextId)
874 .withPriority(XCONNECT_PRIORITY)
875 .fromApp(appId)
876 .makePermanent();
877 return fob;
878 }
879
880 /**
881 * Creates an ACL forwarding objective builder for XConnect.
882 *
883 * @param vlanId cross connect VLAN id
884 * @return forwarding objective builder
885 */
886 private ForwardingObjective.Builder aclObjBuilder(VlanId vlanId) {
887 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
888 sbuilder.matchVlanId(vlanId);
889
890 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
891
892 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
893 fob.withFlag(ForwardingObjective.Flag.VERSATILE)
894 .withSelector(sbuilder.build())
895 .withTreatment(tbuilder.build())
896 .withPriority(XCONNECT_ACL_PRIORITY)
897 .fromApp(appId)
898 .makePermanent();
899 return fob;
900 }
901
902 /**
903 * Creates a filtering objective builder for XConnect.
904 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530905 * @param key XConnect key
Charles Chan8d316332018-06-19 20:31:57 -0700906 * @param port XConnect ports
Charles Chan48df9ad2018-10-30 18:08:59 -0700907 * @param filtered true if this is a filtered port
Charles Chan8d316332018-06-19 20:31:57 -0700908 * @return next objective builder
909 */
Charles Chan48df9ad2018-10-30 18:08:59 -0700910 private FilteringObjective.Builder filterObjBuilder(XconnectKey key, PortNumber port, boolean filtered) {
Charles Chan8d316332018-06-19 20:31:57 -0700911 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
912 fob.withKey(Criteria.matchInPort(port))
Charles Chan8d316332018-06-19 20:31:57 -0700913 .addCondition(Criteria.matchEthDst(MacAddress.NONE))
914 .withPriority(XCONNECT_PRIORITY);
Charles Chan48df9ad2018-10-30 18:08:59 -0700915 if (filtered) {
916 fob.addCondition(Criteria.matchVlanId(key.vlanId()));
917 } else {
918 fob.addCondition(Criteria.matchVlanId(VlanId.ANY));
919 }
Charles Chan8d316332018-06-19 20:31:57 -0700920 return fob.permit().fromApp(appId);
921 }
922
923 /**
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530924 * Updates L2 flooding groups; add pair link into L2 flooding group of given xconnect vlan.
Charles Chan8d316332018-06-19 20:31:57 -0700925 *
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530926 * @param deviceId Device ID
927 * @param port Port details
928 * @param vlanId VLAN ID
929 * @param install Whether to add or revoke pair link addition to flooding group
Charles Chan8d316332018-06-19 20:31:57 -0700930 */
pier6fd24fd2018-11-27 11:23:50 -0800931 private void updateL2Flooding(DeviceId deviceId, PortNumber port, VlanId vlanId, boolean install) {
932 XconnectKey key = new XconnectKey(deviceId, vlanId);
933 // Ensure leadership on device
934 if (!isLocalLeader(deviceId)) {
935 log.debug("Abort updating L2Flood {}: {}", key, ERROR_NOT_LEADER);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530936 return;
Charles Chan8d316332018-06-19 20:31:57 -0700937 }
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530938
939 // Locate L2 flooding group details for given xconnect vlan
pier6fd24fd2018-11-27 11:23:50 -0800940 int nextId = Versioned.valueOrElse(xconnectNextObjStore.get(key), -1);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530941 if (nextId == -1) {
942 log.debug("XConnect vlan {} broadcast group for device {} doesn't exists. " +
943 "Aborting pair group linking.", vlanId, deviceId);
944 return;
945 }
946
947 // Add pairing-port group to flooding group
948 TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
949 // treatment.popVlan();
950 treatment.setOutput(port);
951 ObjectiveContext context = new DefaultObjectiveContext(
952 (objective) ->
953 log.debug("Pair port added/removed to vlan {} next objective {} on {}",
954 vlanId, nextId, deviceId),
955 (objective, error) ->
956 log.warn("Failed adding/removing pair port to vlan {} next objective {} on {}." +
957 "Error : {}", vlanId, nextId, deviceId, error)
958 );
959 NextObjective.Builder vlanNextObjectiveBuilder = DefaultNextObjective.builder()
960 .withId(nextId)
961 .withType(NextObjective.Type.BROADCAST)
962 .fromApp(srService.appId())
963 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId).build())
964 .addTreatment(treatment.build());
965 if (install) {
966 flowObjectiveService.next(deviceId, vlanNextObjectiveBuilder.addToExisting(context));
967 } else {
968 flowObjectiveService.next(deviceId, vlanNextObjectiveBuilder.removeFromExisting(context));
969 }
970 log.debug("Submitted next objective {} for vlan: {} in device {}",
971 nextId, vlanId, deviceId);
Charles Chan8d316332018-06-19 20:31:57 -0700972 }
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530973
974 /**
975 * Populate L2 multicast rule on given deviceId that matches given mac, given vlan and
976 * output to given port's L2 mulitcast group.
977 *
978 * @param deviceId Device ID
979 * @param pairPort Pair port number
980 * @param vlanId VLAN ID
981 * @param accessPorts List of access ports to be added into L2 multicast group
982 */
pier6fd24fd2018-11-27 11:23:50 -0800983 private void populateL2Multicast(DeviceId deviceId, PortNumber pairPort,
984 VlanId vlanId, List<PortNumber> accessPorts) {
985 // Ensure enough rights to program pair device
986 if (!srService.shouldProgram(deviceId)) {
987 log.debug("Abort populate L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
988 return;
989 }
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530990
991 boolean multicastGroupExists = true;
992 int vlanMulticastNextId;
pier6fd24fd2018-11-27 11:23:50 -0800993 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +0530994
995 // Step 1 : Populate single homed access ports into vlan's L2 multicast group
996 NextObjective.Builder vlanMulticastNextObjBuilder = DefaultNextObjective
997 .builder()
998 .withType(NextObjective.Type.BROADCAST)
999 .fromApp(srService.appId())
1000 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId)
1001 .matchEthDst(MacAddress.IPV4_MULTICAST).build());
pier6fd24fd2018-11-27 11:23:50 -08001002 vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301003 if (vlanMulticastNextId == -1) {
1004 // Vlan's L2 multicast group doesn't exist; create it, update store and add pair port as sub-group
1005 multicastGroupExists = false;
1006 vlanMulticastNextId = flowObjectiveService.allocateNextId();
pier6fd24fd2018-11-27 11:23:50 -08001007 addMulticastGroupNextObjectiveId(key, vlanMulticastNextId);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301008 vlanMulticastNextObjBuilder.addTreatment(
1009 DefaultTrafficTreatment.builder().popVlan().setOutput(pairPort).build()
1010 );
1011 }
1012 vlanMulticastNextObjBuilder.withId(vlanMulticastNextId);
pier6fd24fd2018-11-27 11:23:50 -08001013 int nextId = vlanMulticastNextId;
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301014 accessPorts.forEach(p -> {
1015 TrafficTreatment.Builder egressAction = DefaultTrafficTreatment.builder();
1016 // Do vlan popup action based on interface configuration
1017 if (interfaceService.getInterfacesByPort(new ConnectPoint(deviceId, p))
1018 .stream().noneMatch(i -> i.vlanTagged().contains(vlanId))) {
1019 egressAction.popVlan();
1020 }
1021 egressAction.setOutput(p);
1022 vlanMulticastNextObjBuilder.addTreatment(egressAction.build());
pier6fd24fd2018-11-27 11:23:50 -08001023 addMulticastGroupPort(key, p);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301024 });
1025 ObjectiveContext context = new DefaultObjectiveContext(
1026 (objective) ->
1027 log.debug("L2 multicast group installed/updated. "
1028 + "NextObject Id {} on {} for subnet {} ",
1029 nextId, deviceId, vlanId),
1030 (objective, error) ->
1031 log.warn("L2 multicast group failed to install/update. "
1032 + " NextObject Id {} on {} for subnet {} : {}",
1033 nextId, deviceId, vlanId, error)
1034 );
1035 if (!multicastGroupExists) {
1036 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.add(context));
1037
1038 // Step 2 : Populate ACL rule; selector = vlan + pair-port, output = vlan L2 multicast group
1039 TrafficSelector.Builder multicastSelector = DefaultTrafficSelector.builder();
1040 multicastSelector.matchEthType(Ethernet.TYPE_VLAN);
1041 multicastSelector.matchInPort(pairPort);
1042 multicastSelector.matchVlanId(vlanId);
1043 ForwardingObjective.Builder vlanMulticastForwardingObj = DefaultForwardingObjective.builder()
1044 .withFlag(ForwardingObjective.Flag.VERSATILE)
1045 .nextStep(vlanMulticastNextId)
1046 .withSelector(multicastSelector.build())
1047 .withPriority(100)
1048 .fromApp(srService.appId())
1049 .makePermanent();
1050 context = new DefaultObjectiveContext(
1051 (objective) -> log.debug("L2 multicasting versatile rule for device {}, port/vlan {}/{} populated",
1052 deviceId,
1053 pairPort,
1054 vlanId),
1055 (objective, error) -> log.warn("Failed to populate L2 multicasting versatile rule for device {}, " +
1056 "ports/vlan {}/{}: {}", deviceId, pairPort, vlanId, error));
1057 flowObjectiveService.forward(deviceId, vlanMulticastForwardingObj.add(context));
1058 } else {
1059 // L2_MULTICAST & BROADCAST are similar structure in subgroups; so going with BROADCAST type.
1060 vlanMulticastNextObjBuilder.withType(NextObjective.Type.BROADCAST);
1061 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.addToExisting(context));
1062 }
1063 }
1064
1065 /**
1066 * Removes access ports from VLAN L2 multicast group on given deviceId.
1067 *
1068 * @param deviceId Device ID
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301069 * @param vlanId VLAN ID
1070 * @param accessPorts List of access ports to be added into L2 multicast group
1071 */
pier6fd24fd2018-11-27 11:23:50 -08001072 private void revokeL2Multicast(DeviceId deviceId, VlanId vlanId, List<PortNumber> accessPorts) {
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301073 // Ensure enough rights to program pair device
1074 if (!srService.shouldProgram(deviceId)) {
pier6fd24fd2018-11-27 11:23:50 -08001075 log.debug("Abort revoke L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301076 return;
1077 }
1078
pier6fd24fd2018-11-27 11:23:50 -08001079 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
1080
1081 int vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301082 if (vlanMulticastNextId == -1) {
1083 return;
1084 }
1085 NextObjective.Builder vlanMulticastNextObjBuilder = DefaultNextObjective
1086 .builder()
1087 .withType(NextObjective.Type.BROADCAST)
1088 .fromApp(srService.appId())
1089 .withMeta(DefaultTrafficSelector.builder().matchVlanId(vlanId).build())
1090 .withId(vlanMulticastNextId);
1091 accessPorts.forEach(p -> {
1092 TrafficTreatment.Builder egressAction = DefaultTrafficTreatment.builder();
1093 // Do vlan popup action based on interface configuration
1094 if (interfaceService.getInterfacesByPort(new ConnectPoint(deviceId, p))
1095 .stream().noneMatch(i -> i.vlanTagged().contains(vlanId))) {
1096 egressAction.popVlan();
1097 }
1098 egressAction.setOutput(p);
1099 vlanMulticastNextObjBuilder.addTreatment(egressAction.build());
pier6fd24fd2018-11-27 11:23:50 -08001100 removeMulticastGroupPort(key, p);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301101 });
1102 ObjectiveContext context = new DefaultObjectiveContext(
1103 (objective) ->
1104 log.debug("L2 multicast group installed/updated. "
1105 + "NextObject Id {} on {} for subnet {} ",
1106 vlanMulticastNextId, deviceId, vlanId),
1107 (objective, error) ->
1108 log.warn("L2 multicast group failed to install/update. "
1109 + " NextObject Id {} on {} for subnet {} : {}",
1110 vlanMulticastNextId, deviceId, vlanId, error)
1111 );
1112 flowObjectiveService.next(deviceId, vlanMulticastNextObjBuilder.removeFromExisting(context));
1113 }
1114
1115 /**
1116 * Cleans up VLAN L2 multicast group on given deviceId. ACL rules for the group will also be deleted.
1117 * Normally multicast group is not removed if it contains access ports; which can be forced
1118 * by "force" flag
1119 *
1120 * @param deviceId Device ID
1121 * @param pairPort Pair port number
1122 * @param vlanId VLAN ID
1123 * @param force Forceful removal
1124 */
1125 private void cleanupL2MulticastRule(DeviceId deviceId, PortNumber pairPort, VlanId vlanId, boolean force) {
1126
1127 // Ensure enough rights to program pair device
1128 if (!srService.shouldProgram(deviceId)) {
pier6fd24fd2018-11-27 11:23:50 -08001129 log.debug("Abort cleanup L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301130 return;
1131 }
1132
pier6fd24fd2018-11-27 11:23:50 -08001133 VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);
1134
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301135 // Ensure L2 multicast group doesn't contain access ports
pier6fd24fd2018-11-27 11:23:50 -08001136 if (hasAccessPortInMulticastGroup(key, pairPort) && !force) {
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301137 return;
1138 }
1139
1140 // Load L2 multicast group details
pier6fd24fd2018-11-27 11:23:50 -08001141 int vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301142 if (vlanMulticastNextId == -1) {
1143 return;
1144 }
1145
1146 // Step 1 : Clear ACL rule; selector = vlan + pair-port, output = vlan L2 multicast group
1147 TrafficSelector.Builder l2MulticastSelector = DefaultTrafficSelector.builder();
1148 l2MulticastSelector.matchEthType(Ethernet.TYPE_VLAN);
1149 l2MulticastSelector.matchInPort(pairPort);
1150 l2MulticastSelector.matchVlanId(vlanId);
1151 ForwardingObjective.Builder vlanMulticastForwardingObj = DefaultForwardingObjective.builder()
1152 .withFlag(ForwardingObjective.Flag.VERSATILE)
1153 .nextStep(vlanMulticastNextId)
1154 .withSelector(l2MulticastSelector.build())
1155 .withPriority(100)
1156 .fromApp(srService.appId())
1157 .makePermanent();
1158 ObjectiveContext context = new DefaultObjectiveContext(
1159 (objective) -> log.debug("L2 multicasting rule for device {}, port/vlan {}/{} deleted", deviceId,
1160 pairPort, vlanId),
1161 (objective, error) -> log.warn("Failed to delete L2 multicasting rule for device {}, " +
1162 "ports/vlan {}/{}: {}", deviceId, pairPort, vlanId, error));
1163 flowObjectiveService.forward(deviceId, vlanMulticastForwardingObj.remove(context));
1164
1165 // Step 2 : Clear L2 multicast group associated with vlan
1166 NextObjective.Builder l2MulticastGroupBuilder = DefaultNextObjective
1167 .builder()
1168 .withId(vlanMulticastNextId)
1169 .withType(NextObjective.Type.BROADCAST)
1170 .fromApp(srService.appId())
1171 .withMeta(DefaultTrafficSelector.builder()
1172 .matchVlanId(vlanId)
1173 .matchEthDst(MacAddress.IPV4_MULTICAST).build())
1174 .addTreatment(DefaultTrafficTreatment.builder().popVlan().setOutput(pairPort).build());
1175 context = new DefaultObjectiveContext(
1176 (objective) ->
1177 log.debug("L2 multicast group with NextObject Id {} deleted on {} for subnet {} ",
1178 vlanMulticastNextId, deviceId, vlanId),
1179 (objective, error) ->
1180 log.warn("L2 multicast group with NextObject Id {} failed to delete on {} for subnet {} : {}",
1181 vlanMulticastNextId, deviceId, vlanId, error)
1182 );
1183 flowObjectiveService.next(deviceId, l2MulticastGroupBuilder.remove(context));
1184
1185 // Finally clear store.
pier6fd24fd2018-11-27 11:23:50 -08001186 removeMulticastGroup(key);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301187 }
1188
pier6fd24fd2018-11-27 11:23:50 -08001189 private int getMulticastGroupNextObjectiveId(VlanNextObjectiveStoreKey key) {
1190 return Versioned.valueOrElse(xconnectMulticastNextStore.get(key), -1);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301191 }
1192
pier6fd24fd2018-11-27 11:23:50 -08001193 private void addMulticastGroupNextObjectiveId(VlanNextObjectiveStoreKey key, int nextId) {
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301194 if (nextId == -1) {
1195 return;
1196 }
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301197 xconnectMulticastNextStore.put(key, nextId);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301198 }
1199
pier6fd24fd2018-11-27 11:23:50 -08001200 private void addMulticastGroupPort(VlanNextObjectiveStoreKey groupKey, PortNumber port) {
1201 xconnectMulticastPortsStore.compute(groupKey, (key, ports) -> {
1202 if (ports == null) {
1203 ports = Lists.newArrayList();
1204 }
1205 ports.add(port);
1206 return ports;
1207 });
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301208 }
1209
pier6fd24fd2018-11-27 11:23:50 -08001210 private void removeMulticastGroupPort(VlanNextObjectiveStoreKey groupKey, PortNumber port) {
1211 xconnectMulticastPortsStore.compute(groupKey, (key, ports) -> {
1212 if (ports != null && !ports.isEmpty()) {
1213 ports.remove(port);
1214 }
1215 return ports;
1216 });
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301217 }
1218
pier6fd24fd2018-11-27 11:23:50 -08001219 private void removeMulticastGroup(VlanNextObjectiveStoreKey groupKey) {
1220 xconnectMulticastPortsStore.remove(groupKey);
1221 xconnectMulticastNextStore.remove(groupKey);
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301222 }
1223
pier6fd24fd2018-11-27 11:23:50 -08001224 private boolean hasAccessPortInMulticastGroup(VlanNextObjectiveStoreKey groupKey, PortNumber pairPort) {
1225 List<PortNumber> ports = Versioned.valueOrElse(xconnectMulticastPortsStore.get(groupKey), ImmutableList.of());
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301226 return ports.stream().anyMatch(p -> !p.equals(pairPort));
1227 }
1228
pier6fd24fd2018-11-27 11:23:50 -08001229 // Custom-built function, when the device is not available we need a fallback mechanism
1230 private boolean isLocalLeader(DeviceId deviceId) {
1231 if (!mastershipService.isLocalMaster(deviceId)) {
1232 // When the device is available we just check the mastership
1233 if (deviceService.isAvailable(deviceId)) {
1234 return false;
1235 }
1236 // Fallback with Leadership service - device id is used as topic
1237 NodeId leader = leadershipService.runForLeadership(
1238 deviceId.toString()).leaderNodeId();
1239 // Verify if this node is the leader
1240 return clusterService.getLocalNode().id().equals(leader);
1241 }
1242 return true;
1243 }
1244
Charles Chan445659f2019-01-02 13:46:16 -08001245 private Set<PortNumber> getPhysicalPorts(DeviceId deviceId, XconnectEndpoint endpoint) {
1246 if (endpoint.type() == XconnectEndpoint.Type.PORT) {
1247 PortNumber port = ((XconnectPortEndpoint) endpoint).port();
1248 return Sets.newHashSet(port);
Charles Chan48df9ad2018-10-30 18:08:59 -07001249 }
Charles Chan445659f2019-01-02 13:46:16 -08001250 if (endpoint.type() == XconnectEndpoint.Type.LOAD_BALANCER) {
Charles Chanc0a499b2019-01-16 15:30:39 -08001251 PortLoadBalancerId portLoadBalancerId = new PortLoadBalancerId(deviceId,
1252 ((XconnectLoadBalancerEndpoint) endpoint).key());
1253 Set<PortNumber> ports = portLoadBalancerService.getPortLoadBalancer(portLoadBalancerId).ports();
Charles Chan445659f2019-01-02 13:46:16 -08001254 return Sets.newHashSet(ports);
Charles Chan48df9ad2018-10-30 18:08:59 -07001255 }
Charles Chan48df9ad2018-10-30 18:08:59 -07001256 return Sets.newHashSet();
1257 }
1258
Charles Chan445659f2019-01-02 13:46:16 -08001259 private NextTreatment getNextTreatment(DeviceId deviceId, XconnectEndpoint endpoint, boolean reserve) {
1260 if (endpoint.type() == XconnectEndpoint.Type.PORT) {
1261 PortNumber port = ((XconnectPortEndpoint) endpoint).port();
1262 return DefaultNextTreatment.of(DefaultTrafficTreatment.builder().setOutput(port).build());
Charles Chan48df9ad2018-10-30 18:08:59 -07001263 }
Charles Chan445659f2019-01-02 13:46:16 -08001264 if (endpoint.type() == XconnectEndpoint.Type.LOAD_BALANCER) {
Charles Chanc0a499b2019-01-16 15:30:39 -08001265 PortLoadBalancerId portLoadBalancerId = new PortLoadBalancerId(deviceId,
1266 ((XconnectLoadBalancerEndpoint) endpoint).key());
1267 NextTreatment idNextTreatment = IdNextTreatment.of(portLoadBalancerService
1268 .getPortLoadBalancerNext(portLoadBalancerId));
pier567465b2018-11-24 11:16:28 -08001269 // Reserve only one time during next objective creation
1270 if (reserve) {
Charles Chanc0a499b2019-01-16 15:30:39 -08001271 if (!portLoadBalancerService.reserve(portLoadBalancerId, appId)) {
1272 log.warn("Reservation failed for {}", portLoadBalancerId);
pier567465b2018-11-24 11:16:28 -08001273 idNextTreatment = null;
1274 }
1275 }
1276 return idNextTreatment;
Charles Chan48df9ad2018-10-30 18:08:59 -07001277 }
Charles Chan48df9ad2018-10-30 18:08:59 -07001278 return null;
1279 }
pier567465b2018-11-24 11:16:28 -08001280
Charles Chanc0a499b2019-01-16 15:30:39 -08001281 private class InternalPortLoadBalancerListener implements PortLoadBalancerListener {
1282 // Populate xconnect once portloadbalancer is available
pier567465b2018-11-24 11:16:28 -08001283 @Override
Charles Chanc0a499b2019-01-16 15:30:39 -08001284 public void event(PortLoadBalancerEvent event) {
1285 portLoadBalancerExecutor.execute(() -> dequeue(event.subject().portLoadBalancerId()));
pier567465b2018-11-24 11:16:28 -08001286 }
Charles Chanc0a499b2019-01-16 15:30:39 -08001287 // When we receive INSTALLED port load balancing is ready
pier567465b2018-11-24 11:16:28 -08001288 @Override
Charles Chanc0a499b2019-01-16 15:30:39 -08001289 public boolean isRelevant(PortLoadBalancerEvent event) {
1290 return event.type() == PortLoadBalancerEvent.Type.INSTALLED;
pier567465b2018-11-24 11:16:28 -08001291 }
1292 }
1293
1294 // Invalidate the cache and re-start the xconnect installation
Charles Chanc0a499b2019-01-16 15:30:39 -08001295 private void dequeue(PortLoadBalancerId portLoadBalancerId) {
1296 XconnectKey xconnectKey = portLoadBalancerCache.getIfPresent(portLoadBalancerId);
pier567465b2018-11-24 11:16:28 -08001297 if (xconnectKey == null) {
Charles Chanc0a499b2019-01-16 15:30:39 -08001298 log.trace("{} not present in the cache", portLoadBalancerId);
pier567465b2018-11-24 11:16:28 -08001299 return;
1300 }
Charles Chanc0a499b2019-01-16 15:30:39 -08001301 log.debug("Dequeue {}", portLoadBalancerId);
1302 portLoadBalancerCache.invalidate(portLoadBalancerId);
Charles Chan445659f2019-01-02 13:46:16 -08001303 Set<XconnectEndpoint> endpoints = Versioned.valueOrNull(xconnectStore.get(xconnectKey));
1304 if (endpoints == null || endpoints.isEmpty()) {
1305 log.warn("Endpoints not found for XConnect {}", xconnectKey);
pier567465b2018-11-24 11:16:28 -08001306 return;
1307 }
Charles Chan445659f2019-01-02 13:46:16 -08001308 populateXConnect(xconnectKey, endpoints);
Charles Chanc0a499b2019-01-16 15:30:39 -08001309 log.trace("PortLoadBalancer cache size {}", portLoadBalancerCache.size());
pier567465b2018-11-24 11:16:28 -08001310 }
1311
Charles Chan8d316332018-06-19 20:31:57 -07001312}