blob: 1d1cc4ee2d6eae4d90324f6c017482aa9842cdcc [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070018import java.util.Collections;
19import java.util.HashSet;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070020import java.util.List;
21import java.util.Map;
22import java.util.Map.Entry;
23import java.util.Optional;
24import java.util.Set;
25import java.util.concurrent.ConcurrentHashMap;
26import java.util.concurrent.ConcurrentLinkedQueue;
27import java.util.concurrent.Executors;
28import java.util.concurrent.ScheduledExecutorService;
29import java.util.concurrent.ScheduledFuture;
30import java.util.concurrent.TimeUnit;
31import java.util.concurrent.atomic.AtomicBoolean;
32import java.util.stream.Collectors;
33
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -070034import com.fasterxml.jackson.databind.node.ObjectNode;
Charles Chan9640c812017-08-23 13:55:39 -070035import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070036import org.apache.felix.scr.annotations.Activate;
37import org.apache.felix.scr.annotations.Component;
38import org.apache.felix.scr.annotations.Deactivate;
39import org.apache.felix.scr.annotations.Reference;
40import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070041import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070042import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080043import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070044import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080045import org.onlab.packet.IPv6;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070046import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070047import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070048import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070049import org.onlab.util.KryoNamespace;
Saurav Das80980c72016-03-23 11:22:49 -070050import org.onosproject.cfg.ComponentConfigService;
sanghob35a6192015-04-01 13:05:26 -070051import org.onosproject.core.ApplicationId;
52import org.onosproject.core.CoreService;
53import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070054import org.onosproject.mastership.MastershipService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070071import org.onosproject.net.device.DeviceEvent;
72import org.onosproject.net.device.DeviceListener;
73import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080074import org.onosproject.net.flow.TrafficSelector;
75import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070076import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080077import org.onosproject.net.host.HostEvent;
78import org.onosproject.net.host.HostListener;
Pier Ventre10bd8d12016-11-26 21:05:22 -080079import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070080import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070081import org.onosproject.net.intf.Interface;
82import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080083import org.onosproject.net.link.LinkEvent;
84import org.onosproject.net.link.LinkListener;
85import org.onosproject.net.link.LinkService;
Charles Chand55e84d2016-03-30 17:54:24 -070086import org.onosproject.net.mcast.McastEvent;
87import org.onosproject.net.mcast.McastListener;
88import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070089import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080090import org.onosproject.net.packet.InboundPacket;
91import org.onosproject.net.packet.PacketContext;
92import org.onosproject.net.packet.PacketProcessor;
93import org.onosproject.net.packet.PacketService;
Pier Ventre42287df2016-11-09 14:17:26 -080094import org.onosproject.net.topology.PathService;
Charles Chand55e84d2016-03-30 17:54:24 -070095import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070096import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070097import org.onosproject.routeservice.RouteEvent;
98import org.onosproject.routeservice.RouteListener;
99import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
101import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800102import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventref34966c2016-11-07 16:21:04 -0800103import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700105import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700106import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700107import org.onosproject.segmentrouting.grouphandler.DestinationSet;
108import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700109import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
110import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700112import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700113import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800114import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700115import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700116import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700117import org.onosproject.store.service.EventuallyConsistentMap;
118import org.onosproject.store.service.EventuallyConsistentMapBuilder;
119import org.onosproject.store.service.StorageService;
120import org.onosproject.store.service.WallClockTimestamp;
sanghob35a6192015-04-01 13:05:26 -0700121import org.slf4j.Logger;
122import org.slf4j.LoggerFactory;
123
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700124import com.google.common.collect.HashMultimap;
125import com.google.common.collect.ImmutableMap;
126import com.google.common.collect.Maps;
127import com.google.common.collect.Multimap;
sanghob35a6192015-04-01 13:05:26 -0700128
Charles Chan3e783d02016-02-26 22:19:52 -0800129import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800130import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700131import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800132
Charles Chane849c192016-01-11 18:28:54 -0800133/**
134 * Segment routing manager.
135 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700136@Service
137@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700138public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700139
Charles Chan2c15aca2016-11-09 20:51:44 -0800140 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700141 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700144 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800147 private NeighbourResolutionService neighbourResolutionService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800150 public PathService pathService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700153 CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700156 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700159 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700162 DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800165 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700168 LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700169
Charles Chan5270ed02016-01-30 23:22:37 -0800170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800171 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800174 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 MulticastRouteService multicastRouteService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
180 TopologyService topologyService;
181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700183 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800186 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800187
Saurav Das80980c72016-03-23 11:22:49 -0700188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800189 public InterfaceService interfaceService;
190
Charles Chan03a73e02016-10-24 14:52:01 -0700191 ArpHandler arpHandler = null;
192 IcmpHandler icmpHandler = null;
193 IpHandler ipHandler = null;
194 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700195 ApplicationId appId;
196 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700197
Charles Chan03a73e02016-10-24 14:52:01 -0700198 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700199 private TunnelHandler tunnelHandler = null;
200 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700201 private InternalPacketProcessor processor = null;
202 private InternalLinkListener linkListener = null;
203 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700204 private AppConfigHandler appCfgHandler = null;
Charles Chan03a73e02016-10-24 14:52:01 -0700205 XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700206 private McastHandler mcastHandler = null;
Charles Chan65238242017-06-22 18:03:14 -0700207 private HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800208 private RouteHandler routeHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800209 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventref34966c2016-11-07 16:21:04 -0800210 private L2TunnelHandler l2TunnelHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700211 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800212 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700213 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
214 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700215 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sanghob35a6192015-04-01 13:05:26 -0700216
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700217 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700218 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700219
Saurav Das4ce45962015-11-24 23:21:05 -0800220 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700221 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800222 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700223 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800224 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800225 new ConcurrentHashMap<>();
226 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700227 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700228 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800229 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700230 EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
231 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800232 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700233 * Per device next objective ID store with (device id + vlanid) as key.
234 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800235 */
Ray Milkeye4afdb52017-04-05 09:42:04 -0700236 EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800237 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800238 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700239 * Per device next objective ID store with (device id + port + treatment + meta) as key.
240 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800241 */
Ray Milkeye4afdb52017-04-05 09:42:04 -0700242 EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800243 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800244
Saurav Dasc88d4662017-05-15 15:34:25 -0700245 // Local store for all links seen and their present status, used for
246 // optimized routing. The existence of the link in the keys is enough to know
247 // if the link has been "seen-before" by this instance of the controller.
248 // The boolean value indicates if the link is currently up or not.
249 // XXX Currently the optimized routing logic depends on "forgetting" a link
250 // when a switch goes down, but "remembering" it when only the link goes down.
251 // Consider changing this logic so we can use the Link Service instead of
252 // a local cache.
253 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
254
Saurav Das4ce45962015-11-24 23:21:05 -0800255 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
256 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700257
Saurav Das7bcbe702017-06-13 15:35:54 -0700258 private AtomicBoolean programmingScheduled = new AtomicBoolean();
259
Charles Chand55e84d2016-03-30 17:54:24 -0700260 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700261 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
262 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700263 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700264 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800265 public SegmentRoutingDeviceConfig createConfig() {
266 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700267 }
268 };
Pier Ventref34966c2016-11-07 16:21:04 -0800269
Charles Chand55e84d2016-03-30 17:54:24 -0700270 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700271 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
272 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700273 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800274 @Override
275 public SegmentRoutingAppConfig createConfig() {
276 return new SegmentRoutingAppConfig();
277 }
278 };
Pier Ventref34966c2016-11-07 16:21:04 -0800279
Charles Chanfc5c7802016-05-17 13:13:55 -0700280 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
281 new ConfigFactory<ApplicationId, XConnectConfig>(
282 SubjectFactories.APP_SUBJECT_FACTORY,
283 XConnectConfig.class, "xconnect") {
284 @Override
285 public XConnectConfig createConfig() {
286 return new XConnectConfig();
287 }
288 };
Pier Ventref34966c2016-11-07 16:21:04 -0800289
Charles Chand55e84d2016-03-30 17:54:24 -0700290 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700291 new ConfigFactory<ApplicationId, McastConfig>(
292 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700293 McastConfig.class, "multicast") {
294 @Override
295 public McastConfig createConfig() {
296 return new McastConfig();
297 }
298 };
299
Pier Ventref34966c2016-11-07 16:21:04 -0800300 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
301 new ConfigFactory<ApplicationId, PwaasConfig>(
302 SubjectFactories.APP_SUBJECT_FACTORY,
303 PwaasConfig.class, "pwaas") {
304 @Override
305 public PwaasConfig createConfig() {
306 return new PwaasConfig();
307 }
308 };
309
Charles Chan65238242017-06-22 18:03:14 -0700310 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700311 private static int numOfEventsQueued = 0;
312 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700313 private static int numOfHandlerExecution = 0;
314 private static int numOfHandlerScheduled = 0;
315
Charles Chan116188d2016-02-18 14:22:42 -0800316 /**
317 * Segment Routing App ID.
318 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800319 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800320
Charles Chane849c192016-01-11 18:28:54 -0800321 /**
322 * The default VLAN ID assigned to the interfaces without subnet config.
323 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800324 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700325
sanghob35a6192015-04-01 13:05:26 -0700326 @Activate
327 protected void activate() {
Charles Chan2c15aca2016-11-09 20:51:44 -0800328 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700329
330 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700331 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700332 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700333 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700334 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700335 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700336 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700337 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700338 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700339
Charles Chan59cc16d2017-02-02 16:20:42 -0800340 log.debug("Creating EC map vlannextobjectivestore");
341 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
342 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
343 vlanNextObjStore = vlanNextObjMapBuilder
344 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700345 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700346 .withTimestampProvider((k, v) -> new WallClockTimestamp())
347 .build();
348
Saurav Das4ce45962015-11-24 23:21:05 -0800349 log.debug("Creating EC map subnetnextobjectivestore");
350 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
351 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
352 portNextObjStore = portNextObjMapBuilder
353 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700354 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800355 .withTimestampProvider((k, v) -> new WallClockTimestamp())
356 .build();
357
sangho0b2b6d12015-05-20 22:16:38 -0700358 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
359 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700360 tunnelStore = tunnelMapBuilder
361 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700362 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700363 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700364 .build();
365
366 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
367 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700368 policyStore = policyMapBuilder
369 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700370 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700371 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700372 .build();
373
Saurav Das80980c72016-03-23 11:22:49 -0700374 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800375 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700376 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800377 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800378 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
379 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700380 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800381 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700382 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800383 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800384 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
385 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800386 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
387 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700388 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700389 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700390 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
391 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800392 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
393 "staleLinkAge", "15000");
394 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
395 "allowDuplicateIps", "false");
Saurav Das80980c72016-03-23 11:22:49 -0700396
Charles Chanb8e10c82015-10-14 11:24:40 -0700397 processor = new InternalPacketProcessor();
398 linkListener = new InternalLinkListener();
399 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700400 appCfgHandler = new AppConfigHandler(this);
401 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700402 mcastHandler = new McastHandler(this);
403 hostHandler = new HostHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700404 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800405 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventref34966c2016-11-07 16:21:04 -0800406 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700407
Charles Chan3e783d02016-02-26 22:19:52 -0800408 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700409 cfgService.registerConfigFactory(deviceConfigFactory);
410 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700411 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700412 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800413 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800414 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700415 packetService.addProcessor(processor, PacketProcessor.director(2));
416 linkService.addListener(linkListener);
417 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700418 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700419 routeService.addListener(routeListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700420
421 cfgListener.configureNetwork();
422
sanghob35a6192015-04-01 13:05:26 -0700423 log.info("Started");
424 }
425
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700426 private KryoNamespace.Builder createSerializer() {
427 return new KryoNamespace.Builder()
428 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700429 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan59cc16d2017-02-02 16:20:42 -0800430 VlanNextObjectiveStoreKey.class,
Saurav Das7bcbe702017-06-13 15:35:54 -0700431 DestinationSet.class,
432 NextNeighbors.class,
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700433 Tunnel.class,
434 DefaultTunnel.class,
435 Policy.class,
436 TunnelPolicy.class,
437 Policy.Type.class,
438 PortNextObjectiveStoreKey.class,
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700439 XConnectStoreKey.class,
440 DefaultL2Tunnel.class,
441 DefaultL2TunnelPolicy.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700442 );
443 }
444
sanghob35a6192015-04-01 13:05:26 -0700445 @Deactivate
446 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700447 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700448 cfgService.unregisterConfigFactory(deviceConfigFactory);
449 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700450 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700451 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800452 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700453
Charles Chanc7a8a682017-06-19 00:43:31 -0700454 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700455 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700456 linkService.removeListener(linkListener);
457 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700458 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700459 routeService.removeListener(routeListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700460
Charles Chan0aa674e2017-02-23 15:44:08 -0800461 neighbourResolutionService.unregisterNeighbourHandlers(appId);
462
sanghob35a6192015-04-01 13:05:26 -0700463 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700464 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700465 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700466 groupHandlerMap.clear();
467
Saurav Das7bcbe702017-06-13 15:35:54 -0700468 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800469 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700470 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700471 tunnelStore.destroy();
472 policyStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700473 log.info("Stopped");
474 }
475
sangho1e575652015-05-14 00:39:53 -0700476 @Override
477 public List<Tunnel> getTunnels() {
478 return tunnelHandler.getTunnels();
479 }
480
481 @Override
sangho71abe1b2015-06-29 14:58:47 -0700482 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
483 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700484 }
485
486 @Override
sangho71abe1b2015-06-29 14:58:47 -0700487 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700488 for (Policy policy: policyHandler.getPolicies()) {
489 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
490 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
491 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
492 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700493 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700494 }
495 }
496 }
sangho71abe1b2015-06-29 14:58:47 -0700497 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700498 }
499
500 @Override
sangho71abe1b2015-06-29 14:58:47 -0700501 public PolicyHandler.Result removePolicy(Policy policy) {
502 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700503 }
504
505 @Override
sangho71abe1b2015-06-29 14:58:47 -0700506 public PolicyHandler.Result createPolicy(Policy policy) {
507 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700508 }
509
510 @Override
511 public List<Policy> getPolicies() {
512 return policyHandler.getPolicies();
513 }
514
Saurav Das59232cf2016-04-27 18:35:50 -0700515 @Override
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700516 public List<DefaultL2Tunnel> getL2Tunnels() {
517 return l2TunnelHandler.getL2Tunnels();
518 }
519
520 @Override
521 public List<DefaultL2TunnelPolicy> getL2Policies() {
522 return l2TunnelHandler.getL2Policies();
523 }
524
525 @Override
526 public L2TunnelHandler.Result addPseudowire(String tunnelId, String pwLabel, String cP1,
527 String cP1InnerVlan, String cP1OuterVlan, String cP2,
528 String cP2InnerVlan, String cP2OuterVlan,
529 String mode, String sdTag) {
530
531 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
532 if (config == null) {
533 log.warn("Configuration for Pwaas class could not be found!");
534 return L2TunnelHandler.Result.CONFIG_NOT_FOUND;
535 }
536
537 ObjectNode object = config.addPseudowire(tunnelId, pwLabel,
538 cP1, cP1InnerVlan, cP1OuterVlan,
539 cP2, cP2InnerVlan, cP2OuterVlan,
540 mode, sdTag);
541 if (object == null) {
542 log.warn("Could not add pseudowire to the configuration!");
543 return L2TunnelHandler.Result.ADDITION_ERROR;
544 }
545
546 // inform everyone about the valid change in the pw configuration
547 cfgService.applyConfig(appId(), PwaasConfig.class, object);
548 return L2TunnelHandler.Result.SUCCESS;
549 }
550
551 @Override
552 public L2TunnelHandler.Result removePseudowire(String pwId) {
553
554 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
555 if (config == null) {
556 log.warn("Configuration for Pwaas class could not be found!");
557 return L2TunnelHandler.Result.CONFIG_NOT_FOUND;
558 }
559
560 ObjectNode object = config.removePseudowire(pwId);
561 if (object == null) {
562 log.warn("Could not delete pseudowire from configuration!");
563 return L2TunnelHandler.Result.REMOVAL_ERROR;
564 }
565
566 // sanity check, this should never fail since we removed a pw
567 // and we always check when we update the configuration
568 config.isValid();
569
570 // inform everyone
571 cfgService.applyConfig(appId(), PwaasConfig.class, object);
572
573 return L2TunnelHandler.Result.SUCCESS;
574 }
575
576 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700577 public void rerouteNetwork() {
578 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700579 }
580
Charles Chanc81c45b2016-10-20 17:02:44 -0700581 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800582 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
583 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chanc81c45b2016-10-20 17:02:44 -0700584 deviceService.getAvailableDevices().forEach(device -> {
585 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
586 });
587 return deviceSubnetMap;
588 }
589
Saurav Dasc88d4662017-05-15 15:34:25 -0700590
591 @Override
592 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
593 if (defaultRoutingHandler != null) {
594 return defaultRoutingHandler.getCurrentEmcpSpgMap();
595 } else {
596 return null;
597 }
598 }
599
600 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700601 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
602 if (dsNextObjStore != null) {
603 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700604 } else {
605 return ImmutableMap.of();
606 }
607 }
608
Saurav Dasceccf242017-08-03 18:30:35 -0700609 @Override
610 public void verifyGroups(DeviceId id) {
611 DefaultGroupHandler gh = groupHandlerMap.get(id);
612 if (gh != null) {
613 gh.triggerBucketCorrector();
614 }
615 }
616
sanghof9d0bf12015-05-19 11:57:42 -0700617 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700618 * Extracts the application ID from the manager.
619 *
620 * @return application ID
621 */
622 public ApplicationId appId() {
623 return appId;
624 }
625
626 /**
627 * Returns the device configuration.
628 *
629 * @return device configuration
630 */
631 public DeviceConfiguration deviceConfiguration() {
632 return deviceConfiguration;
633 }
634
635 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700636 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700637 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700638 *
639 * @return next objective ID store
640 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700641 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
642 dsNextObjStore() {
643 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700644 }
645
646 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700647 * Per device next objective ID store with (device id + vlanid) as key.
648 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700649 *
650 * @return vlan next object store
651 */
652 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
653 return vlanNextObjStore;
654 }
655
656 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700657 * Per device next objective ID store with (device id + port + treatment + meta) as key.
658 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700659 *
660 * @return port next object store.
661 */
662 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
663 return portNextObjStore;
664 }
665
666 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700667 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
668 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700669 *
670 * @return MPLS-ECMP value
671 */
672 public boolean getMplsEcmp() {
673 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
674 .getConfig(this.appId, SegmentRoutingAppConfig.class);
675 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
676 }
677
678 /**
sanghof9d0bf12015-05-19 11:57:42 -0700679 * Returns the tunnel object with the tunnel ID.
680 *
681 * @param tunnelId Tunnel ID
682 * @return Tunnel reference
683 */
sangho1e575652015-05-14 00:39:53 -0700684 public Tunnel getTunnel(String tunnelId) {
685 return tunnelHandler.getTunnel(tunnelId);
686 }
687
Charles Chan7ffd81f2017-02-08 15:52:08 -0800688 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700689 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800690 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800691 * <p>
692 * Only returns the first match if there are multiple untagged VLAN configured
693 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700694 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800695 * @param connectPoint connect point
696 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700697 */
Charles Chan65238242017-06-22 18:03:14 -0700698 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800699 return interfaceService.getInterfacesByPort(connectPoint).stream()
700 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
701 .map(Interface::vlanUntagged)
702 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700703 }
704
sangho1e575652015-05-14 00:39:53 -0700705 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800706 * Returns tagged VLAN configured on given connect point.
707 * <p>
708 * Returns all matches if there are multiple tagged VLAN configured
709 * on the connect point.
710 *
711 * @param connectPoint connect point
712 * @return tagged VLAN or empty set if not configured
713 */
Charles Chan65238242017-06-22 18:03:14 -0700714 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800715 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
716 return interfaces.stream()
717 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700718 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800719 .collect(Collectors.toSet());
720 }
721
722 /**
723 * Returns native VLAN configured on given connect point.
724 * <p>
725 * Only returns the first match if there are multiple native VLAN configured
726 * on the connect point.
727 *
728 * @param connectPoint connect point
729 * @return native VLAN or null if not configured
730 */
Charles Chan65238242017-06-22 18:03:14 -0700731 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800732 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
733 return interfaces.stream()
734 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
735 .map(Interface::vlanNative)
736 .findFirst()
737 .orElse(null);
738 }
739
740 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700741 * Returns internal VLAN for untagged hosts on given connect point.
742 * <p>
743 * The internal VLAN is either vlan-untagged for an access port,
744 * or vlan-native for a trunk port.
745 *
746 * @param connectPoint connect point
747 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
748 */
Charles Chan65238242017-06-22 18:03:14 -0700749 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700750 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
751 VlanId nativeVlanId = getNativeVlanId(connectPoint);
752 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
753 }
754
755 /**
Charles Chan65238242017-06-22 18:03:14 -0700756 * Returns optional pair device ID of given device.
757 *
758 * @param deviceId device ID
759 * @return optional pair device ID. Might be empty if pair device is not configured
760 */
761 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
762 SegmentRoutingDeviceConfig deviceConfig =
763 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
764 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
765 }
766 /**
767 * Returns optional pair device local port of given device.
768 *
769 * @param deviceId device ID
770 * @return optional pair device ID. Might be empty if pair device is not configured
771 */
772 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
773 SegmentRoutingDeviceConfig deviceConfig =
774 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
775 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
776 }
777
778 /**
Charles Chan2fde6d42017-08-23 14:46:43 -0700779 * Determine if current instance is the master of given connect point.
780 *
781 * @param cp connect point
782 * @return true if current instance is the master of given connect point
783 */
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700784 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan2fde6d42017-08-23 14:46:43 -0700785 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
786 if (!isMaster) {
787 log.debug(NOT_MASTER, cp);
788 }
789 return isMaster;
790 }
791
792 /**
Charles Chan9640c812017-08-23 13:55:39 -0700793 * Returns locations of given resolved route.
794 *
795 * @param resolvedRoute resolved route
796 * @return locations of nexthop. Might be empty if next hop is not found
797 */
798 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
799 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
800 return Optional.ofNullable(hostService.getHost(hostId))
801 .map(Host::locations).orElse(Sets.newHashSet())
802 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
803 }
804
805 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800806 * Returns vlan port map of given device.
807 *
808 * @param deviceId device id
809 * @return vlan-port multimap
810 */
811 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
812 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
813
814 interfaceService.getInterfaces().stream()
815 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
816 .forEach(intf -> {
817 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700818 intf.vlanTagged().forEach(vlanTagged ->
819 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
820 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800821 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
822 });
823 vlanPortMap.removeAll(VlanId.NONE);
824
825 return vlanPortMap;
826 }
827
828 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800829 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800830 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700831 *
832 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800833 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800834 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700835 */
Charles Chan65238242017-06-22 18:03:14 -0700836 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700837 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800838 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
839 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700840 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800841 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800842 + "device {} not found", deviceId);
843 return -1;
844 }
845 }
846
847 /**
848 * Returns the next objective ID for the given portNumber, given the treatment.
849 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700850 * would result in different objectives. If the next object does not exist,
851 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800852 *
853 * @param deviceId Device ID
854 * @param portNum port number on device for which NextObjective is queried
855 * @param treatment the actions to apply on the packets (should include outport)
856 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700857 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700858 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800859 */
860 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
861 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700862 TrafficSelector meta,
863 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800864 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
865 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700866 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800867 } else {
Charles Chane849c192016-01-11 18:28:54 -0800868 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
869 + " not found", deviceId);
870 return -1;
871 }
872 }
873
Saurav Dasc88d4662017-05-15 15:34:25 -0700874 /**
875 * Returns the group handler object for the specified device id.
876 *
877 * @param devId the device identifier
878 * @return the groupHandler object for the device id, or null if not found
879 */
Charles Chan65238242017-06-22 18:03:14 -0700880 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700881 return groupHandlerMap.get(devId);
882 }
883
884 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700885 * Returns the default routing handler object.
886 *
887 * @return the default routing handler object
888 */
889 public DefaultRoutingHandler getRoutingHandler() {
890 return defaultRoutingHandler;
891 }
892
893 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700894 * Returns true if this controller instance has seen this link before. The
895 * link may not be currently up, but as long as the link had been seen before
896 * this method will return true. The one exception is when the link was
897 * indeed seen before, but this controller instance was forced to forget it
898 * by a call to purgeSeenLink method.
899 *
900 * @param link the infrastructure link being queried
901 * @return true if this controller instance has seen this link before
902 */
Charles Chan65238242017-06-22 18:03:14 -0700903 boolean isSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700904 return seenLinks.containsKey(link);
905 }
906
907 /**
908 * Updates the seen link store. Updates can be for links that are currently
909 * available or not.
910 *
911 * @param link the link to update in the seen-link local store
912 * @param up the status of the link, true if up, false if down
913 */
Charles Chan65238242017-06-22 18:03:14 -0700914 void updateSeenLink(Link link, boolean up) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700915 seenLinks.put(link, up);
916 }
917
918 /**
919 * Returns the status of a seen-link (up or down). If the link has not
920 * been seen-before, a null object is returned.
921 *
922 * @param link the infrastructure link being queried
923 * @return null if the link was not seen-before;
924 * true if the seen-link is up;
925 * false if the seen-link is down
926 */
Charles Chan65238242017-06-22 18:03:14 -0700927 Boolean isSeenLinkUp(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700928 return seenLinks.get(link);
929 }
930
931 /**
932 * Makes this controller instance forget a previously seen before link.
933 *
934 * @param link the infrastructure link to purge
935 */
Charles Chan65238242017-06-22 18:03:14 -0700936 private void purgeSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700937 seenLinks.remove(link);
938 }
939
940 /**
941 * Returns the status of a link as parallel link. A parallel link
942 * is defined as a link which has common src and dst switches as another
943 * seen-link that is currently enabled. It is not necessary for the link being
944 * queried to be a seen-link.
945 *
946 * @param link the infrastructure link being queried
947 * @return true if a seen-link exists that is up, and shares the
948 * same src and dst switches as the link being queried
949 */
Charles Chan65238242017-06-22 18:03:14 -0700950 private boolean isParallelLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700951 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
952 Link seenLink = seen.getKey();
953 if (seenLink.equals(link)) {
954 continue;
955 }
956 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
957 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
958 seen.getValue()) {
959 return true;
960 }
961 }
962 return false;
963 }
964
Saurav Das7bcbe702017-06-13 15:35:54 -0700965 /**
966 * Returns true if the link being queried is a bidirectional link. A bidi
967 * link is defined as a link, whose reverse link - ie. the link in the reverse
968 * direction - has been seen-before and is up. It is not necessary for the link
969 * being queried to be a seen-link.
970 *
971 * @param link the infrastructure link being queried
972 * @return true if another unidirectional link exists in the reverse direction,
973 * has been seen-before and is up
974 */
975 public boolean isBidirectional(Link link) {
976 Link reverseLink = linkService.getLink(link.dst(), link.src());
977 if (reverseLink == null) {
978 return false;
979 }
980 Boolean result = isSeenLinkUp(reverseLink);
981 if (result == null) {
982 return false;
983 }
984 return result.booleanValue();
985 }
986
987 /**
988 * Determines if the given link should be avoided in routing calculations
989 * by policy or design.
990 *
991 * @param link the infrastructure link being queried
992 * @return true if link should be avoided
993 */
994 public boolean avoidLink(Link link) {
995 // XXX currently only avoids all pair-links. In the future can be
996 // extended to avoid any generic link
997 DeviceId src = link.src().deviceId();
998 PortNumber srcPort = link.src().port();
999 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
1000 log.warn("Device {} not configured..cannot avoid link {}", src, link);
1001 return false;
1002 }
1003 DeviceId pairDev;
1004 PortNumber pairLocalPort, pairRemotePort = null;
1005 try {
1006 pairDev = deviceConfiguration.getPairDeviceId(src);
1007 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
1008 if (pairDev != null) {
1009 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
1010 }
1011 } catch (DeviceConfigNotFoundException e) {
1012 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
1013 src, link);
1014 return false;
1015 }
1016
1017 if (srcPort.equals(pairLocalPort) &&
1018 link.dst().deviceId().equals(pairDev) &&
1019 link.dst().port().equals(pairRemotePort)) {
1020 return true;
1021 }
1022 return false;
1023 }
1024
sanghob35a6192015-04-01 13:05:26 -07001025 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001026 @Override
1027 public void process(PacketContext context) {
1028
1029 if (context.isHandled()) {
1030 return;
1031 }
1032
1033 InboundPacket pkt = context.inPacket();
1034 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001035
1036 if (ethernet == null) {
1037 return;
1038 }
1039
Saurav Das7bcbe702017-06-13 15:35:54 -07001040 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1041 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001042 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001043 log.warn("Received unexpected ARP packet on {}",
1044 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001045 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001046 return;
sanghob35a6192015-04-01 13:05:26 -07001047 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001048 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1049 //ipHandler.addToPacketBuffer(ipv4Packet);
1050 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1051 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001052 } else {
Charles Chan50035632017-01-13 17:20:44 -08001053 // NOTE: We don't support IP learning at this moment so this
1054 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001055 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001056 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001057 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1058 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001059 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001060 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001061 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1062 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1063 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1064 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1065 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1066 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001067 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001068 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001069 }
1070 } else {
1071 // NOTE: We don't support IP learning at this moment so this
1072 // is not necessary. Also it causes duplication of DHCPv6 packets.
1073 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1074 }
sanghob35a6192015-04-01 13:05:26 -07001075 }
1076 }
1077 }
1078
1079 private class InternalLinkListener implements LinkListener {
1080 @Override
1081 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001082 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1083 event.type() == LinkEvent.Type.LINK_UPDATED ||
1084 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001085 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001086 scheduleEventHandlerIfNotScheduled(event);
1087 }
1088 }
1089 }
1090
1091 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001092 @Override
1093 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001094 switch (event.type()) {
1095 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001096 case PORT_UPDATED:
1097 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001098 case DEVICE_UPDATED:
1099 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001100 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001101 scheduleEventHandlerIfNotScheduled(event);
1102 break;
1103 default:
1104 }
1105 }
1106 }
1107
Saurav Das4ce45962015-11-24 23:21:05 -08001108 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001109 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001110 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001111 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001112 numOfEventsQueued++;
1113
1114 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1115 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001116 eventHandlerFuture = executorService
1117 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1118 numOfHandlerScheduled++;
1119 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001120 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001121 numOfEventsQueued,
1122 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001123 }
sanghob35a6192015-04-01 13:05:26 -07001124 }
1125
1126 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001127 @Override
sanghob35a6192015-04-01 13:05:26 -07001128 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001129 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001130 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -08001131 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001132 Event event;
1133 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001134 if (!eventQueue.isEmpty()) {
1135 event = eventQueue.poll();
1136 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001137 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001138 numOfHandlerExecution++;
1139 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1140 numOfHandlerExecution, numOfEventsExecuted);
1141 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001142 }
sangho20eff1d2015-04-13 15:15:58 -07001143 }
Charles Chanb1f8c762017-03-29 16:39:05 -07001144 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1145 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001146 // Note: do not update seenLinks here, otherwise every
1147 // link, even one seen for the first time, will be appear
1148 // to be a previously seen link
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001149 processLinkAdded((Link) event.subject());
1150 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -07001151 Link linkRemoved = (Link) event.subject();
Saurav Dasc88d4662017-05-15 15:34:25 -07001152 if (linkRemoved.type() == Link.Type.DIRECT) {
1153 updateSeenLink(linkRemoved, false);
1154 }
1155 // device availability check helps to ensure that
1156 // multiple link-removed events are actually treated as a
1157 // single switch removed event. purgeSeenLink is necessary
1158 // so we do rerouting (instead of rehashing) when switch
1159 // comes back.
Pier Ventre2c515312016-09-13 21:33:40 -07001160 if (linkRemoved.src().elementId() instanceof DeviceId &&
1161 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001162 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001163 continue;
1164 }
1165 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1166 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001167 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001168 continue;
1169 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001170 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001171 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1172 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1173 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001174 DeviceId deviceId = ((Device) event.subject()).id();
1175 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001176 log.info("Processing device event {} for available device {}",
1177 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001178 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001179 } else {
1180 log.info("Processing device event {} for unavailable device {}",
1181 event.type(), ((Device) event.subject()).id());
1182 processDeviceRemoved((Device) event.subject());
1183 }
Saurav Das1a129a02016-11-18 15:21:57 -08001184 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001185 // typically these calls come when device is added first time
1186 // so port filtering rules are handled at the device_added event.
1187 // port added calls represent all ports on the device,
1188 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001189 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001190 ((DeviceEvent) event).subject().id(),
1191 ((DeviceEvent) event).port().number(),
1192 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001193 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001194 // these calls happen for every subsequent event
1195 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001196 log.info("** PORT UPDATED {}/{} -> {}",
1197 event.subject(),
1198 ((DeviceEvent) event).port(),
1199 event.type());
1200 processPortUpdated(((Device) event.subject()),
1201 ((DeviceEvent) event).port());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001202 } else {
1203 log.warn("Unhandled event type: {}", event.type());
1204 }
sanghob35a6192015-04-01 13:05:26 -07001205 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001206 } catch (Exception e) {
1207 log.error("SegmentRouting event handler "
1208 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -07001209 }
sanghob35a6192015-04-01 13:05:26 -07001210 }
1211 }
1212
sanghob35a6192015-04-01 13:05:26 -07001213 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001214 log.info("** LINK ADDED {}", link.toString());
Saurav Dasc88d4662017-05-15 15:34:25 -07001215 if (link.type() != Link.Type.DIRECT) {
1216 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1217 // if BDDP is received before LLDP. We can safely ignore that
1218 // until the LLDP is received and the link is marked as DIRECT.
1219 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1220 link.src(), link.dst(), link.type());
1221 return;
1222 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001223 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1224 updateSeenLink(link, true);
1225 // XXX revisit - what about devicePortMap
1226 log.warn("Source device of this link is not configured.. "
1227 + "not processing further");
1228 return;
1229 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001230
1231 //Irrespective of whether the local is a MASTER or not for this device,
1232 //create group handler instance and push default TTP flow rules if needed,
1233 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001234 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1235 .deviceId());
1236 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001237 groupHandler.portUpForLink(link);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001238 } else {
Saurav Das9df5b7c2017-08-14 16:44:43 -07001239 // XXX revisit/cleanup
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001240 Device device = deviceService.getDevice(link.src().deviceId());
1241 if (device != null) {
1242 log.warn("processLinkAdded: Link Added "
1243 + "Notification without Device Added "
1244 + "event, still handling it");
1245 processDeviceAdded(device);
1246 groupHandler = groupHandlerMap.get(link.src()
1247 .deviceId());
Saurav Dasc88d4662017-05-15 15:34:25 -07001248 groupHandler.portUpForLink(link);
sanghob35a6192015-04-01 13:05:26 -07001249 }
1250 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001251
Saurav Das7bcbe702017-06-13 15:35:54 -07001252 /*// process link only if it is bidirectional
1253 if (!isBidirectional(link)) {
1254 log.debug("Link not bidirectional.. waiting for other direction "
1255 + "src {} --> dst {} ", link.dst(), link.src());
1256 // note that if we are not processing for routing, it should at least
1257 // be considered a seen-link
1258 updateSeenLink(link, true);
1259 return;
1260 }
1261 TO DO this ensure that rehash is still done correctly even if link is
1262 not processed for rerouting - perhaps rehash in both directions when
1263 it ultimately becomes bidi?
1264 */
1265
1266 log.debug("Starting optimized route population process for link "
1267 + "{} --> {}", link.src(), link.dst());
Saurav Dasc88d4662017-05-15 15:34:25 -07001268 boolean seenBefore = isSeenLink(link);
1269 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das7bcbe702017-06-13 15:35:54 -07001270
1271 // It's possible that linkUp causes no route-path change as ECMP graph does
1272 // not change if the link is a parallel link (same src-dst as another link.
1273 // However we still need to update ECMP hash groups to include new buckets
1274 // for the link that has come up.
Saurav Dasc88d4662017-05-15 15:34:25 -07001275 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001276 if (!seenBefore && isParallelLink(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001277 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das7bcbe702017-06-13 15:35:54 -07001278 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001279 groupHandler.retryHash(link, false, true);
1280 } else {
1281 //seen before-link
1282 if (isParallelLink(link)) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001283 log.debug("Attempting retryHash for paralled seen-before "
1284 + "link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001285 groupHandler.retryHash(link, false, false);
1286 }
1287 }
1288 }
Charles Chan2199c302016-04-23 17:36:10 -07001289
1290 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -07001291 }
1292
1293 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001294 log.info("** LINK REMOVED {}", link.toString());
Saurav Dasc88d4662017-05-15 15:34:25 -07001295 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1296
1297 // update local groupHandler stores
sangho834e4b02015-05-01 09:38:25 -07001298 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1299 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001300 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1301 isParallelLink(link)) {
Saurav Das9df5b7c2017-08-14 16:44:43 -07001302 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001303 groupHandler.retryHash(link, true, false);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001304 } else {
1305 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1306 (mastershipService.isLocalMaster(link.src().deviceId()))
1307 ? "not parallel" : "not master");
Saurav Dasc88d4662017-05-15 15:34:25 -07001308 }
1309 // ensure local stores are updated
1310 groupHandler.portDown(link.src().port());
1311 } else {
1312 log.warn("group handler not found for dev:{} when removing link: {}",
1313 link.src().deviceId(), link);
sangho834e4b02015-05-01 09:38:25 -07001314 }
Charles Chan2199c302016-04-23 17:36:10 -07001315
1316 mcastHandler.processLinkDown(link);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -07001317 l2TunnelHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -07001318 }
1319
1320 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001321 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001322
1323 // NOTE: Punt ARP/NDP even when the device is not configured.
1324 // Host learning without network config is required for CORD config generator.
1325 routingRulePopulator.populateIpPunts(device.id());
1326 routingRulePopulator.populateArpNdpPunts(device.id());
1327
Charles Chan0b4e6182015-11-03 10:42:14 -08001328 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001329 log.warn("Device configuration unavailable. Device {} will be "
1330 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001331 return;
1332 }
Charles Chan2199c302016-04-23 17:36:10 -07001333 processDeviceAddedInternal(device.id());
1334 }
1335
1336 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001337 // Irrespective of whether the local is a MASTER or not for this device,
1338 // we need to create a SR-group-handler instance. This is because in a
1339 // multi-instance setup, any instance can initiate forwarding/next-objectives
1340 // for any switch (even if this instance is a SLAVE or not even connected
1341 // to the switch). To handle this, a default-group-handler instance is necessary
1342 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001343 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1344 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001345 DefaultGroupHandler groupHandler;
1346 try {
1347 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001348 createGroupHandler(deviceId,
1349 appId,
1350 deviceConfiguration,
1351 linkService,
1352 flowObjectiveService,
1353 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001354 } catch (DeviceConfigNotFoundException e) {
1355 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1356 return;
1357 }
Charles Chan2199c302016-04-23 17:36:10 -07001358 log.debug("updating groupHandlerMap with new config for device: {}",
1359 deviceId);
1360 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001361 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001362
Charles Chan2199c302016-04-23 17:36:10 -07001363 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001364 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001365 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001366 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001367 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001368 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001369 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001370 }
Charles Chan5270ed02016-01-30 23:22:37 -08001371
Charles Chan03a73e02016-10-24 14:52:01 -07001372 appCfgHandler.init(deviceId);
1373 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001374 }
1375
Saurav Das80980c72016-03-23 11:22:49 -07001376 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001377 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001378 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1379 .forEach(entry -> {
Saurav Das7bcbe702017-06-13 15:35:54 -07001380 dsNextObjStore.remove(entry.getKey());
Saurav Das80980c72016-03-23 11:22:49 -07001381 });
Charles Chan59cc16d2017-02-02 16:20:42 -08001382 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001383 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001384 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001385 portNextObjStore.entrySet().stream()
1386 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001387 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chaned3742352017-06-15 00:44:51 -07001388
1389 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1390 key.dst().deviceId().equals(device.id()));
1391
Saurav Dasceccf242017-08-03 18:30:35 -07001392 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1393 if (gh != null) {
1394 gh.shutdown();
1395 }
Saurav Das80980c72016-03-23 11:22:49 -07001396 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Dasc88d4662017-05-15 15:34:25 -07001397 // Note that a switch going down is associated with all of its links
1398 // going down as well, but it is treated as a single switch down event
1399 // while the link-downs are ignored.
1400 defaultRoutingHandler
1401 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan2199c302016-04-23 17:36:10 -07001402 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001403 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -07001404 }
1405
Saurav Das1a129a02016-11-18 15:21:57 -08001406 private void processPortUpdated(Device device, Port port) {
1407 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1408 log.warn("Device configuration uploading. Not handling port event for"
1409 + "dev: {} port: {}", device.id(), port.number());
1410 return;
1411 }
Saurav Das018605f2017-02-18 14:05:44 -08001412
1413 if (!mastershipService.isLocalMaster(device.id())) {
1414 log.debug("Not master for dev:{} .. not handling port updated event"
1415 + "for port {}", device.id(), port.number());
1416 return;
1417 }
1418
1419 // first we handle filtering rules associated with the port
1420 if (port.isEnabled()) {
1421 log.info("Switchport {}/{} enabled..programming filters",
1422 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001423 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001424 } else {
1425 log.info("Switchport {}/{} disabled..removing filters",
1426 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001427 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001428 }
Saurav Das1a129a02016-11-18 15:21:57 -08001429
1430 // portUpdated calls are for ports that have gone down or up. For switch
1431 // to switch ports, link-events should take care of any re-routing or
1432 // group editing necessary for port up/down. Here we only process edge ports
1433 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001434 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1435 VlanId untaggedVlan = getUntaggedVlanId(cp);
1436 VlanId nativeVlan = getNativeVlanId(cp);
1437 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001438
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001439 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001440 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001441 + "dev/port: {}/{}", device.id(), port.number());
1442 return;
1443 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001444 if (untaggedVlan != null) {
1445 processEdgePort(device, port, untaggedVlan, true);
1446 }
1447 if (nativeVlan != null) {
1448 processEdgePort(device, port, nativeVlan, true);
1449 }
1450 if (!taggedVlans.isEmpty()) {
1451 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1452 }
Saurav Das1a129a02016-11-18 15:21:57 -08001453 }
1454
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001455 private void processEdgePort(Device device, Port port, VlanId vlanId,
1456 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001457 boolean portUp = port.isEnabled();
1458 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001459 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001460 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001461 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001462 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001463 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001464 }
1465
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001466 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001467 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001468 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001469 } else {
1470 log.warn("Group handler not found for dev:{}. Not handling edge port"
1471 + " {} event for port:{}", device.id(),
1472 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001473 }
1474 }
sangho1e575652015-05-14 00:39:53 -07001475
Charles Chan27fe1a52017-10-20 16:06:55 -07001476 private void createOrUpdateDeviceConfiguration() {
1477 if (deviceConfiguration == null) {
1478 deviceConfiguration = new DeviceConfiguration(this);
1479 } else {
1480 deviceConfiguration.updateConfig();
1481 }
1482 }
1483
Pier Ventre10bd8d12016-11-26 21:05:22 -08001484 /**
1485 * Registers the given connect point with the NRS, this is necessary
1486 * to receive the NDP and ARP packets from the NRS.
1487 *
1488 * @param portToRegister connect point to register
1489 */
1490 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001491 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001492 portToRegister,
1493 neighbourHandler,
1494 appId
1495 );
1496 }
1497
Charles Chand6832882015-10-05 17:50:33 -07001498 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001499 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001500 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001501
Charles Chane849c192016-01-11 18:28:54 -08001502 /**
1503 * Constructs the internal network config listener.
1504 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001505 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001506 */
Charles Chan65238242017-06-22 18:03:14 -07001507 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001508 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001509 }
1510
Charles Chane849c192016-01-11 18:28:54 -08001511 /**
1512 * Reads network config and initializes related data structure accordingly.
1513 */
Charles Chan4636be02015-10-07 14:21:45 -07001514 public void configureNetwork() {
Charles Chan27fe1a52017-10-20 16:06:55 -07001515 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001516
Charles Chan2c15aca2016-11-09 20:51:44 -08001517 arpHandler = new ArpHandler(srManager);
1518 icmpHandler = new IcmpHandler(srManager);
1519 ipHandler = new IpHandler(srManager);
1520 routingRulePopulator = new RoutingRulePopulator(srManager);
1521 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001522
1523 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1524 groupHandlerMap, tunnelStore);
1525 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1526 flowObjectiveService,
1527 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001528 // add a small delay to absorb multiple network config added notifications
1529 if (!programmingScheduled.get()) {
1530 programmingScheduled.set(true);
1531 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1532 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001533 }
Charles Chan2199c302016-04-23 17:36:10 -07001534 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001535 }
1536
Charles Chand6832882015-10-05 17:50:33 -07001537 @Override
1538 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001539 // TODO move this part to NetworkConfigEventHandler
1540 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1541 switch (event.type()) {
1542 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001543 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001544 configureNetwork();
1545 break;
1546 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001547 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001548 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001549 // TODO support dynamic configuration
1550 break;
1551 default:
1552 break;
1553 }
1554 } else if (event.configClass().equals(InterfaceConfig.class)) {
1555 switch (event.type()) {
1556 case CONFIG_ADDED:
1557 log.info("Interface Config added for {}", event.subject());
1558 configureNetwork();
1559 break;
1560 case CONFIG_UPDATED:
1561 log.info("Interface Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001562 createOrUpdateDeviceConfiguration();
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001563
1564 // Following code will be uncommented when [CORD-634] is fully implemented.
1565 // [CORD-634] Add dynamic config support for interfaces
1566 updateInterface((InterfaceConfig) event.config().get(),
1567 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001568 // TODO support dynamic configuration
1569 break;
1570 default:
1571 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001572 }
Charles Chan5270ed02016-01-30 23:22:37 -08001573 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001574 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001575 switch (event.type()) {
1576 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001577 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001578 break;
1579 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001580 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001581 break;
1582 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001583 appCfgHandler.processAppConfigRemoved(event);
1584 break;
1585 default:
1586 break;
1587 }
Charles Chan03a73e02016-10-24 14:52:01 -07001588 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001589 } else if (event.configClass().equals(XConnectConfig.class)) {
1590 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1591 switch (event.type()) {
1592 case CONFIG_ADDED:
1593 xConnectHandler.processXConnectConfigAdded(event);
1594 break;
1595 case CONFIG_UPDATED:
1596 xConnectHandler.processXConnectConfigUpdated(event);
1597 break;
1598 case CONFIG_REMOVED:
1599 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001600 break;
1601 default:
1602 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001603 }
Pier Ventref34966c2016-11-07 16:21:04 -08001604 } else if (event.configClass().equals(PwaasConfig.class)) {
1605 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1606 switch (event.type()) {
1607 case CONFIG_ADDED:
1608 l2TunnelHandler.processPwaasConfigAdded(event);
1609 break;
1610 case CONFIG_UPDATED:
1611 l2TunnelHandler.processPwaasConfigUpdated(event);
1612 break;
1613 case CONFIG_REMOVED:
1614 l2TunnelHandler.processPwaasConfigRemoved(event);
1615 break;
1616 default:
1617 break;
1618 }
Charles Chand6832882015-10-05 17:50:33 -07001619 }
1620 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001621
1622 private final class ConfigChange implements Runnable {
1623 @Override
1624 public void run() {
1625 programmingScheduled.set(false);
1626 for (Device device : deviceService.getDevices()) {
1627 processDeviceAdded(device);
1628 }
1629 defaultRoutingHandler.startPopulationProcess();
1630 }
1631 }
Charles Chand6832882015-10-05 17:50:33 -07001632 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001633
1634 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001635 @Override
1636 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001637 switch (event.type()) {
1638 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001639 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001640 break;
1641 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001642 hostHandler.processHostMovedEvent(event);
Charles Chan2fde6d42017-08-23 14:46:43 -07001643 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001644 break;
1645 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001646 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001647 break;
1648 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001649 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001650 break;
1651 default:
1652 log.warn("Unsupported host event type: {}", event.type());
1653 break;
1654 }
1655 }
1656 }
1657
Charles Chand55e84d2016-03-30 17:54:24 -07001658 private class InternalMcastListener implements McastListener {
1659 @Override
1660 public void event(McastEvent event) {
1661 switch (event.type()) {
1662 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001663 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001664 break;
1665 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001666 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001667 break;
1668 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001669 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001670 break;
1671 case ROUTE_ADDED:
1672 case ROUTE_REMOVED:
1673 default:
1674 break;
1675 }
1676 }
1677 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001678
Charles Chan03a73e02016-10-24 14:52:01 -07001679 private class InternalRouteEventListener implements RouteListener {
1680 @Override
1681 public void event(RouteEvent event) {
1682 switch (event.type()) {
1683 case ROUTE_ADDED:
1684 routeHandler.processRouteAdded(event);
1685 break;
1686 case ROUTE_UPDATED:
1687 routeHandler.processRouteUpdated(event);
1688 break;
1689 case ROUTE_REMOVED:
1690 routeHandler.processRouteRemoved(event);
1691 break;
Charles Chan2fde6d42017-08-23 14:46:43 -07001692 case ALTERNATIVE_ROUTES_CHANGED:
1693 routeHandler.processAlternativeRoutesChanged(event);
1694 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001695 default:
1696 break;
1697 }
1698 }
1699 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001700
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001701 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1702 try {
1703 Set<Interface> intfs = conf.getInterfaces();
1704 Set<Interface> prevIntfs = prevConf.getInterfaces();
1705
1706 // Now we only handle one interface config at each port.
1707 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1708 log.warn("Interface update aborted - one at a time is allowed, " +
1709 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1710 return;
1711 }
1712
1713 Interface intf = intfs.stream().findFirst().get();
1714 Interface prevIntf = prevIntfs.stream().findFirst().get();
1715
1716 DeviceId deviceId = intf.connectPoint().deviceId();
1717 PortNumber portNum = intf.connectPoint().port();
1718
1719 if (!mastershipService.isLocalMaster(deviceId)) {
1720 log.debug("CONFIG_UPDATED event for interfaces should be " +
1721 "handled by master node for device {}", deviceId);
1722 return;
1723 }
1724
1725 removeSubnetConfig(prevIntf.connectPoint(),
1726 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1727 new HashSet<>(intf.ipAddressesList())));
1728
1729 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1730 // RemoveVlanNative
1731 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1732 }
1733
1734 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1735 // RemoveVlanTagged
1736 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1737 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1738 );
1739 }
1740
1741 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1742 // RemoveVlanUntagged
1743 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1744 }
1745
1746 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1747 // AddVlanNative
1748 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1749 }
1750
1751 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1752 // AddVlanTagged
1753 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1754 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1755 );
1756 }
1757
1758 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1759 // AddVlanUntagged
1760 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1761 }
1762 addSubnetConfig(prevIntf.connectPoint(),
1763 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1764 new HashSet<>(prevIntf.ipAddressesList())));
1765 } catch (ConfigException e) {
1766 log.error("Error in configuration");
1767 }
1768 }
1769
1770 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1771 VlanId vlanId, boolean pushVlan, boolean install) {
1772 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1773 if (grpHandler == null) {
1774 log.warn("Failed to retrieve group handler for device {}", deviceId);
1775 return;
1776 }
1777
1778 // Update filtering objective for a single port
1779 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1780
1781 // Update filtering objective for multicast ingress port
1782 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1783
1784 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1785
1786 if (nextId != -1 && !install) {
1787 // Update next objective for a single port as an output port
1788 // Remove a single port from L2FG
1789 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1790 // Remove L2 Bridging rule and L3 Unicast rule to the host
1791 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1792 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1793 // only if there is no port configured on that VLAN ID
1794 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1795 // Remove broadcast forwarding rule for the VLAN
1796 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1797 // Remove L2FG for VLAN
1798 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1799 } else {
1800 // Remove L2IG of the port
1801 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1802 }
1803 } else if (install) {
1804 if (nextId != -1) {
1805 // Add a single port to L2FG
1806 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1807 } else {
1808 // Create L2FG for VLAN
1809 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1810 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1811 }
1812 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1813 } else {
1814 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1815 }
1816 }
1817
1818 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1819 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1820 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1821
1822 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1823 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1824 .filter(intf -> !intf.connectPoint().equals(cp))
1825 .flatMap(intf -> intf.ipAddressesList().stream())
1826 .collect(Collectors.toSet());
1827 // 1. Partial subnet population
1828 // Remove routing rules for removed subnet from previous configuration,
1829 // which does not also exist in other interfaces in the same device
1830 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1831 .map(InterfaceIpAddress::subnetAddress)
1832 .collect(Collectors.toSet());
1833
1834 defaultRoutingHandler.revokeSubnet(
1835 ipPrefixSet.stream()
1836 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1837 .collect(Collectors.toSet()));
1838
1839 // 2. Interface IP punts
1840 // Remove IP punts for old Intf address
1841 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1842 .map(InterfaceIpAddress::ipAddress)
1843 .collect(Collectors.toSet());
1844 ipAddressSet.stream()
1845 .map(InterfaceIpAddress::ipAddress)
1846 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1847 .forEach(interfaceIpAddress ->
1848 routingRulePopulator.revokeSingleIpPunts(
1849 cp.deviceId(), interfaceIpAddress));
1850
1851 // 3. Host unicast routing rule
1852 // Remove unicast routing rule
1853 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1854 }
1855
1856 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1857 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1858 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1859
1860 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1861 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1862 .filter(intf -> !intf.connectPoint().equals(cp))
1863 .flatMap(intf -> intf.ipAddressesList().stream())
1864 .collect(Collectors.toSet());
1865 // 1. Partial subnet population
1866 // Add routing rules for newly added subnet, which does not also exist in
1867 // other interfaces in the same device
1868 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1869 .map(InterfaceIpAddress::subnetAddress)
1870 .collect(Collectors.toSet());
1871
1872 defaultRoutingHandler.populateSubnet(
1873 Collections.singleton(cp),
1874 ipPrefixSet.stream()
1875 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1876 .collect(Collectors.toSet()));
1877
1878 // 2. Interface IP punts
1879 // Add IP punts for new Intf address
1880 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1881 .map(InterfaceIpAddress::ipAddress)
1882 .collect(Collectors.toSet());
1883 ipAddressSet.stream()
1884 .map(InterfaceIpAddress::ipAddress)
1885 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1886 .forEach(interfaceIpAddress ->
1887 routingRulePopulator.populateSingleIpPunts(
1888 cp.deviceId(), interfaceIpAddress));
1889
1890 // 3. Host unicast routing rule
1891 // Add unicast routing rule
1892 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1893 }
sanghob35a6192015-04-01 13:05:26 -07001894}