blob: 5d04301e8120309aa28221f932670e3f80c0b6e4 [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 Hyun5f1def82017-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
Charles Chanb15d0102017-08-23 13:55:39 -070034import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070035import org.apache.felix.scr.annotations.Activate;
36import org.apache.felix.scr.annotations.Component;
37import org.apache.felix.scr.annotations.Deactivate;
38import org.apache.felix.scr.annotations.Reference;
39import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070040import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070041import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080042import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070043import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080044import org.onlab.packet.IPv6;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070045import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070046import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070047import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070048import org.onlab.util.KryoNamespace;
Saurav Das80980c72016-03-23 11:22:49 -070049import org.onosproject.cfg.ComponentConfigService;
sanghob35a6192015-04-01 13:05:26 -070050import org.onosproject.core.ApplicationId;
51import org.onosproject.core.CoreService;
52import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070053import org.onosproject.mastership.MastershipService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080054import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070055import org.onosproject.net.Device;
56import org.onosproject.net.DeviceId;
Charles Chanb15d0102017-08-23 13:55:39 -070057import org.onosproject.net.Host;
58import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070059import org.onosproject.net.Link;
60import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080061import org.onosproject.net.PortNumber;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070062import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070063import org.onosproject.net.config.ConfigFactory;
64import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070065import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070066import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070067import org.onosproject.net.config.basics.InterfaceConfig;
68import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070069import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070070import org.onosproject.net.device.DeviceEvent;
71import org.onosproject.net.device.DeviceListener;
72import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080073import org.onosproject.net.flow.TrafficSelector;
74import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070075import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080076import org.onosproject.net.host.HostEvent;
77import org.onosproject.net.host.HostListener;
Pier Ventre10bd8d12016-11-26 21:05:22 -080078import org.onosproject.net.host.HostService;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070079import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070080import org.onosproject.net.intf.Interface;
81import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080082import org.onosproject.net.link.LinkEvent;
83import org.onosproject.net.link.LinkListener;
84import org.onosproject.net.link.LinkService;
Charles Chand55e84d2016-03-30 17:54:24 -070085import org.onosproject.net.mcast.McastEvent;
86import org.onosproject.net.mcast.McastListener;
87import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070088import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080089import org.onosproject.net.packet.InboundPacket;
90import org.onosproject.net.packet.PacketContext;
91import org.onosproject.net.packet.PacketProcessor;
92import org.onosproject.net.packet.PacketService;
Pier Ventre42287df2016-11-09 14:17:26 -080093import org.onosproject.net.topology.PathService;
Charles Chand55e84d2016-03-30 17:54:24 -070094import org.onosproject.net.topology.TopologyService;
Charles Chanb15d0102017-08-23 13:55:39 -070095import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070096import org.onosproject.routeservice.RouteEvent;
97import org.onosproject.routeservice.RouteListener;
98import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -070099import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
100import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800101import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventref34966c2016-11-07 16:21:04 -0800102import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700103import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700104import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700105import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700106import org.onosproject.segmentrouting.grouphandler.DestinationSet;
107import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700108import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700109import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700110import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800111import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700112import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700113import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700114import org.onosproject.store.service.EventuallyConsistentMap;
115import org.onosproject.store.service.EventuallyConsistentMapBuilder;
116import org.onosproject.store.service.StorageService;
117import org.onosproject.store.service.WallClockTimestamp;
sanghob35a6192015-04-01 13:05:26 -0700118import org.slf4j.Logger;
119import org.slf4j.LoggerFactory;
120
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700121import com.google.common.collect.HashMultimap;
122import com.google.common.collect.ImmutableMap;
123import com.google.common.collect.Maps;
124import com.google.common.collect.Multimap;
sanghob35a6192015-04-01 13:05:26 -0700125
Charles Chan3e783d02016-02-26 22:19:52 -0800126import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800127import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700128import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800129
Charles Chane849c192016-01-11 18:28:54 -0800130/**
131 * Segment routing manager.
132 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700133@Service
134@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700135public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700136
Charles Chan2c15aca2016-11-09 20:51:44 -0800137 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan23686832017-08-23 14:46:43 -0700138 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700141 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800144 private NeighbourResolutionService neighbourResolutionService;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800147 public PathService pathService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700150 CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700153 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700156 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700159 DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800162 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700165 LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700166
Charles Chan5270ed02016-01-30 23:22:37 -0800167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800168 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700169
170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800171 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
174 MulticastRouteService multicastRouteService;
175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 TopologyService topologyService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700180 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800183 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800184
Saurav Das80980c72016-03-23 11:22:49 -0700185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800186 public InterfaceService interfaceService;
187
Charles Chan03a73e02016-10-24 14:52:01 -0700188 ArpHandler arpHandler = null;
189 IcmpHandler icmpHandler = null;
190 IpHandler ipHandler = null;
191 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700192 ApplicationId appId;
193 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700194
Charles Chan03a73e02016-10-24 14:52:01 -0700195 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700196 private TunnelHandler tunnelHandler = null;
197 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700198 private InternalPacketProcessor processor = null;
199 private InternalLinkListener linkListener = null;
200 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700201 private AppConfigHandler appCfgHandler = null;
Charles Chan03a73e02016-10-24 14:52:01 -0700202 XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700203 private McastHandler mcastHandler = null;
Charles Chan65238242017-06-22 18:03:14 -0700204 private HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800205 private RouteHandler routeHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800206 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventref34966c2016-11-07 16:21:04 -0800207 private L2TunnelHandler l2TunnelHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700208 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800209 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700210 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
211 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700212 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sanghob35a6192015-04-01 13:05:26 -0700213
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700214 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700215 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700216
Saurav Das4ce45962015-11-24 23:21:05 -0800217 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700218 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800219 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700220 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800221 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800222 new ConcurrentHashMap<>();
223 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700224 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5deb3232017-08-22 15:07:34 -0700225 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800226 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700227 EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
228 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800229 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700230 * Per device next objective ID store with (device id + vlanid) as key.
231 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800232 */
Ray Milkeye4afdb52017-04-05 09:42:04 -0700233 EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800234 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800235 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700236 * Per device next objective ID store with (device id + port + treatment + meta) as key.
237 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800238 */
Ray Milkeye4afdb52017-04-05 09:42:04 -0700239 EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800240 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800241
Saurav Dasc88d4662017-05-15 15:34:25 -0700242 // Local store for all links seen and their present status, used for
243 // optimized routing. The existence of the link in the keys is enough to know
244 // if the link has been "seen-before" by this instance of the controller.
245 // The boolean value indicates if the link is currently up or not.
246 // XXX Currently the optimized routing logic depends on "forgetting" a link
247 // when a switch goes down, but "remembering" it when only the link goes down.
248 // Consider changing this logic so we can use the Link Service instead of
249 // a local cache.
250 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
251
Saurav Das4ce45962015-11-24 23:21:05 -0800252 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
253 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700254
Saurav Das7bcbe702017-06-13 15:35:54 -0700255 private AtomicBoolean programmingScheduled = new AtomicBoolean();
256
Charles Chand55e84d2016-03-30 17:54:24 -0700257 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700258 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
259 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700260 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700261 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800262 public SegmentRoutingDeviceConfig createConfig() {
263 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700264 }
265 };
Pier Ventref34966c2016-11-07 16:21:04 -0800266
Charles Chand55e84d2016-03-30 17:54:24 -0700267 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700268 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
269 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700270 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800271 @Override
272 public SegmentRoutingAppConfig createConfig() {
273 return new SegmentRoutingAppConfig();
274 }
275 };
Pier Ventref34966c2016-11-07 16:21:04 -0800276
Charles Chanfc5c7802016-05-17 13:13:55 -0700277 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
278 new ConfigFactory<ApplicationId, XConnectConfig>(
279 SubjectFactories.APP_SUBJECT_FACTORY,
280 XConnectConfig.class, "xconnect") {
281 @Override
282 public XConnectConfig createConfig() {
283 return new XConnectConfig();
284 }
285 };
Pier Ventref34966c2016-11-07 16:21:04 -0800286
Charles Chand55e84d2016-03-30 17:54:24 -0700287 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700288 new ConfigFactory<ApplicationId, McastConfig>(
289 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700290 McastConfig.class, "multicast") {
291 @Override
292 public McastConfig createConfig() {
293 return new McastConfig();
294 }
295 };
296
Pier Ventref34966c2016-11-07 16:21:04 -0800297 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
298 new ConfigFactory<ApplicationId, PwaasConfig>(
299 SubjectFactories.APP_SUBJECT_FACTORY,
300 PwaasConfig.class, "pwaas") {
301 @Override
302 public PwaasConfig createConfig() {
303 return new PwaasConfig();
304 }
305 };
306
Charles Chan65238242017-06-22 18:03:14 -0700307 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700308 private static int numOfEventsQueued = 0;
309 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700310 private static int numOfHandlerExecution = 0;
311 private static int numOfHandlerScheduled = 0;
312
Charles Chan116188d2016-02-18 14:22:42 -0800313 /**
314 * Segment Routing App ID.
315 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800316 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800317
Charles Chane849c192016-01-11 18:28:54 -0800318 /**
319 * The default VLAN ID assigned to the interfaces without subnet config.
320 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800321 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700322
sanghob35a6192015-04-01 13:05:26 -0700323 @Activate
324 protected void activate() {
Charles Chan2c15aca2016-11-09 20:51:44 -0800325 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700326
327 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700328 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700329 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700330 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700331 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700332 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700333 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700334 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700335 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700336
Charles Chan59cc16d2017-02-02 16:20:42 -0800337 log.debug("Creating EC map vlannextobjectivestore");
338 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
339 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
340 vlanNextObjStore = vlanNextObjMapBuilder
341 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700342 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700343 .withTimestampProvider((k, v) -> new WallClockTimestamp())
344 .build();
345
Saurav Das4ce45962015-11-24 23:21:05 -0800346 log.debug("Creating EC map subnetnextobjectivestore");
347 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
348 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
349 portNextObjStore = portNextObjMapBuilder
350 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700351 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800352 .withTimestampProvider((k, v) -> new WallClockTimestamp())
353 .build();
354
sangho0b2b6d12015-05-20 22:16:38 -0700355 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
356 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700357 tunnelStore = tunnelMapBuilder
358 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700359 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700360 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700361 .build();
362
363 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
364 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700365 policyStore = policyMapBuilder
366 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700367 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700368 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700369 .build();
370
Saurav Das80980c72016-03-23 11:22:49 -0700371 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800372 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700373 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800374 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800375 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
376 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700377 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800378 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700379 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800380 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800381 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
382 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800383 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
384 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700385 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700386 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700387 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
388 "multihomingEnabled", "true");
Charles Chanfd892012017-11-29 19:54:20 -0800389 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
390 "staleLinkAge", "15000");
391 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
392 "allowDuplicateIps", "false");
Saurav Das80980c72016-03-23 11:22:49 -0700393
Charles Chanb8e10c82015-10-14 11:24:40 -0700394 processor = new InternalPacketProcessor();
395 linkListener = new InternalLinkListener();
396 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700397 appCfgHandler = new AppConfigHandler(this);
398 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700399 mcastHandler = new McastHandler(this);
400 hostHandler = new HostHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700401 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800402 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventref34966c2016-11-07 16:21:04 -0800403 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700404
Charles Chan3e783d02016-02-26 22:19:52 -0800405 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700406 cfgService.registerConfigFactory(deviceConfigFactory);
407 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700408 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700409 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800410 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800411 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700412 packetService.addProcessor(processor, PacketProcessor.director(2));
413 linkService.addListener(linkListener);
414 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700415 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700416 routeService.addListener(routeListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700417
418 cfgListener.configureNetwork();
419
sanghob35a6192015-04-01 13:05:26 -0700420 log.info("Started");
421 }
422
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700423 private KryoNamespace.Builder createSerializer() {
424 return new KryoNamespace.Builder()
425 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700426 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan59cc16d2017-02-02 16:20:42 -0800427 VlanNextObjectiveStoreKey.class,
Saurav Das7bcbe702017-06-13 15:35:54 -0700428 DestinationSet.class,
429 NextNeighbors.class,
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700430 Tunnel.class,
431 DefaultTunnel.class,
432 Policy.class,
433 TunnelPolicy.class,
434 Policy.Type.class,
435 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700436 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700437 );
438 }
439
sanghob35a6192015-04-01 13:05:26 -0700440 @Deactivate
441 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700442 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700443 cfgService.unregisterConfigFactory(deviceConfigFactory);
444 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700445 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700446 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800447 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700448
Charles Chanc7a8a682017-06-19 00:43:31 -0700449 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700450 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700451 linkService.removeListener(linkListener);
452 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700453 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700454 routeService.removeListener(routeListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700455
Charles Chan0aa674e2017-02-23 15:44:08 -0800456 neighbourResolutionService.unregisterNeighbourHandlers(appId);
457
sanghob35a6192015-04-01 13:05:26 -0700458 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700459 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700460 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700461 groupHandlerMap.clear();
462
Saurav Das7bcbe702017-06-13 15:35:54 -0700463 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800464 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700465 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700466 tunnelStore.destroy();
467 policyStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700468 log.info("Stopped");
469 }
470
sangho1e575652015-05-14 00:39:53 -0700471 @Override
472 public List<Tunnel> getTunnels() {
473 return tunnelHandler.getTunnels();
474 }
475
476 @Override
sangho71abe1b2015-06-29 14:58:47 -0700477 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
478 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700479 }
480
481 @Override
sangho71abe1b2015-06-29 14:58:47 -0700482 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700483 for (Policy policy: policyHandler.getPolicies()) {
484 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
485 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
486 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
487 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700488 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700489 }
490 }
491 }
sangho71abe1b2015-06-29 14:58:47 -0700492 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700493 }
494
495 @Override
sangho71abe1b2015-06-29 14:58:47 -0700496 public PolicyHandler.Result removePolicy(Policy policy) {
497 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700498 }
499
500 @Override
sangho71abe1b2015-06-29 14:58:47 -0700501 public PolicyHandler.Result createPolicy(Policy policy) {
502 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700503 }
504
505 @Override
506 public List<Policy> getPolicies() {
507 return policyHandler.getPolicies();
508 }
509
Saurav Das59232cf2016-04-27 18:35:50 -0700510 @Override
511 public void rerouteNetwork() {
512 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700513 }
514
Charles Chanc81c45b2016-10-20 17:02:44 -0700515 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800516 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
517 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chanc81c45b2016-10-20 17:02:44 -0700518 deviceService.getAvailableDevices().forEach(device -> {
519 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
520 });
521 return deviceSubnetMap;
522 }
523
Saurav Dasc88d4662017-05-15 15:34:25 -0700524
525 @Override
526 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
527 if (defaultRoutingHandler != null) {
528 return defaultRoutingHandler.getCurrentEmcpSpgMap();
529 } else {
530 return null;
531 }
532 }
533
534 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700535 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
536 if (dsNextObjStore != null) {
537 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700538 } else {
539 return ImmutableMap.of();
540 }
541 }
542
Saurav Dasceccf242017-08-03 18:30:35 -0700543 @Override
544 public void verifyGroups(DeviceId id) {
545 DefaultGroupHandler gh = groupHandlerMap.get(id);
546 if (gh != null) {
547 gh.triggerBucketCorrector();
548 }
549 }
550
sanghof9d0bf12015-05-19 11:57:42 -0700551 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700552 * Extracts the application ID from the manager.
553 *
554 * @return application ID
555 */
556 public ApplicationId appId() {
557 return appId;
558 }
559
560 /**
561 * Returns the device configuration.
562 *
563 * @return device configuration
564 */
565 public DeviceConfiguration deviceConfiguration() {
566 return deviceConfiguration;
567 }
568
569 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700570 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5deb3232017-08-22 15:07:34 -0700571 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700572 *
573 * @return next objective ID store
574 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700575 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
576 dsNextObjStore() {
577 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700578 }
579
580 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700581 * Per device next objective ID store with (device id + vlanid) as key.
582 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700583 *
584 * @return vlan next object store
585 */
586 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
587 return vlanNextObjStore;
588 }
589
590 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700591 * Per device next objective ID store with (device id + port + treatment + meta) as key.
592 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700593 *
594 * @return port next object store.
595 */
596 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
597 return portNextObjStore;
598 }
599
600 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700601 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
602 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700603 *
604 * @return MPLS-ECMP value
605 */
606 public boolean getMplsEcmp() {
607 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
608 .getConfig(this.appId, SegmentRoutingAppConfig.class);
609 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
610 }
611
612 /**
sanghof9d0bf12015-05-19 11:57:42 -0700613 * Returns the tunnel object with the tunnel ID.
614 *
615 * @param tunnelId Tunnel ID
616 * @return Tunnel reference
617 */
sangho1e575652015-05-14 00:39:53 -0700618 public Tunnel getTunnel(String tunnelId) {
619 return tunnelHandler.getTunnel(tunnelId);
620 }
621
Charles Chan7ffd81f2017-02-08 15:52:08 -0800622 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700623 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800624 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800625 * <p>
626 * Only returns the first match if there are multiple untagged VLAN configured
627 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700628 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800629 * @param connectPoint connect point
630 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700631 */
Charles Chan65238242017-06-22 18:03:14 -0700632 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800633 return interfaceService.getInterfacesByPort(connectPoint).stream()
634 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
635 .map(Interface::vlanUntagged)
636 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700637 }
638
sangho1e575652015-05-14 00:39:53 -0700639 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800640 * Returns tagged VLAN configured on given connect point.
641 * <p>
642 * Returns all matches if there are multiple tagged VLAN configured
643 * on the connect point.
644 *
645 * @param connectPoint connect point
646 * @return tagged VLAN or empty set if not configured
647 */
Charles Chan65238242017-06-22 18:03:14 -0700648 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800649 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
650 return interfaces.stream()
651 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700652 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800653 .collect(Collectors.toSet());
654 }
655
656 /**
657 * Returns native VLAN configured on given connect point.
658 * <p>
659 * Only returns the first match if there are multiple native VLAN configured
660 * on the connect point.
661 *
662 * @param connectPoint connect point
663 * @return native VLAN or null if not configured
664 */
Charles Chan65238242017-06-22 18:03:14 -0700665 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800666 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
667 return interfaces.stream()
668 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
669 .map(Interface::vlanNative)
670 .findFirst()
671 .orElse(null);
672 }
673
674 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700675 * Returns internal VLAN for untagged hosts on given connect point.
676 * <p>
677 * The internal VLAN is either vlan-untagged for an access port,
678 * or vlan-native for a trunk port.
679 *
680 * @param connectPoint connect point
681 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
682 */
Charles Chan65238242017-06-22 18:03:14 -0700683 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700684 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
685 VlanId nativeVlanId = getNativeVlanId(connectPoint);
686 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
687 }
688
689 /**
Charles Chan65238242017-06-22 18:03:14 -0700690 * Returns optional pair device ID of given device.
691 *
692 * @param deviceId device ID
693 * @return optional pair device ID. Might be empty if pair device is not configured
694 */
695 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
696 SegmentRoutingDeviceConfig deviceConfig =
697 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
698 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
699 }
700 /**
701 * Returns optional pair device local port of given device.
702 *
703 * @param deviceId device ID
704 * @return optional pair device ID. Might be empty if pair device is not configured
705 */
706 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
707 SegmentRoutingDeviceConfig deviceConfig =
708 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
709 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
710 }
711
712 /**
Charles Chan23686832017-08-23 14:46:43 -0700713 * Determine if current instance is the master of given connect point.
714 *
715 * @param cp connect point
716 * @return true if current instance is the master of given connect point
717 */
718 boolean isMasterOf(ConnectPoint cp) {
719 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
720 if (!isMaster) {
721 log.debug(NOT_MASTER, cp);
722 }
723 return isMaster;
724 }
725
726 /**
Charles Chanb15d0102017-08-23 13:55:39 -0700727 * Returns locations of given resolved route.
728 *
729 * @param resolvedRoute resolved route
730 * @return locations of nexthop. Might be empty if next hop is not found
731 */
732 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
733 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
734 return Optional.ofNullable(hostService.getHost(hostId))
735 .map(Host::locations).orElse(Sets.newHashSet())
736 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
737 }
738
739 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800740 * Returns vlan port map of given device.
741 *
742 * @param deviceId device id
743 * @return vlan-port multimap
744 */
745 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
746 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
747
748 interfaceService.getInterfaces().stream()
749 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
750 .forEach(intf -> {
751 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700752 intf.vlanTagged().forEach(vlanTagged ->
753 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
754 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800755 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
756 });
757 vlanPortMap.removeAll(VlanId.NONE);
758
759 return vlanPortMap;
760 }
761
762 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800763 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800764 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700765 *
766 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800767 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800768 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700769 */
Charles Chan65238242017-06-22 18:03:14 -0700770 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700771 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800772 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
773 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700774 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800775 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800776 + "device {} not found", deviceId);
777 return -1;
778 }
779 }
780
781 /**
782 * Returns the next objective ID for the given portNumber, given the treatment.
783 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700784 * would result in different objectives. If the next object does not exist,
785 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800786 *
787 * @param deviceId Device ID
788 * @param portNum port number on device for which NextObjective is queried
789 * @param treatment the actions to apply on the packets (should include outport)
790 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700791 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700792 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800793 */
794 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
795 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700796 TrafficSelector meta,
797 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800798 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
799 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700800 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800801 } else {
Charles Chane849c192016-01-11 18:28:54 -0800802 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
803 + " not found", deviceId);
804 return -1;
805 }
806 }
807
Saurav Dasc88d4662017-05-15 15:34:25 -0700808 /**
809 * Returns the group handler object for the specified device id.
810 *
811 * @param devId the device identifier
812 * @return the groupHandler object for the device id, or null if not found
813 */
Charles Chan65238242017-06-22 18:03:14 -0700814 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700815 return groupHandlerMap.get(devId);
816 }
817
818 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700819 * Returns the default routing handler object.
820 *
821 * @return the default routing handler object
822 */
823 public DefaultRoutingHandler getRoutingHandler() {
824 return defaultRoutingHandler;
825 }
826
827 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700828 * Returns true if this controller instance has seen this link before. The
829 * link may not be currently up, but as long as the link had been seen before
830 * this method will return true. The one exception is when the link was
831 * indeed seen before, but this controller instance was forced to forget it
832 * by a call to purgeSeenLink method.
833 *
834 * @param link the infrastructure link being queried
835 * @return true if this controller instance has seen this link before
836 */
Charles Chan65238242017-06-22 18:03:14 -0700837 boolean isSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700838 return seenLinks.containsKey(link);
839 }
840
841 /**
842 * Updates the seen link store. Updates can be for links that are currently
843 * available or not.
844 *
845 * @param link the link to update in the seen-link local store
846 * @param up the status of the link, true if up, false if down
847 */
Charles Chan65238242017-06-22 18:03:14 -0700848 void updateSeenLink(Link link, boolean up) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700849 seenLinks.put(link, up);
850 }
851
852 /**
853 * Returns the status of a seen-link (up or down). If the link has not
854 * been seen-before, a null object is returned.
855 *
856 * @param link the infrastructure link being queried
857 * @return null if the link was not seen-before;
858 * true if the seen-link is up;
859 * false if the seen-link is down
860 */
Charles Chan65238242017-06-22 18:03:14 -0700861 Boolean isSeenLinkUp(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700862 return seenLinks.get(link);
863 }
864
865 /**
866 * Makes this controller instance forget a previously seen before link.
867 *
868 * @param link the infrastructure link to purge
869 */
Charles Chan65238242017-06-22 18:03:14 -0700870 private void purgeSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700871 seenLinks.remove(link);
872 }
873
874 /**
875 * Returns the status of a link as parallel link. A parallel link
876 * is defined as a link which has common src and dst switches as another
877 * seen-link that is currently enabled. It is not necessary for the link being
878 * queried to be a seen-link.
879 *
880 * @param link the infrastructure link being queried
881 * @return true if a seen-link exists that is up, and shares the
882 * same src and dst switches as the link being queried
883 */
Charles Chan65238242017-06-22 18:03:14 -0700884 private boolean isParallelLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700885 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
886 Link seenLink = seen.getKey();
887 if (seenLink.equals(link)) {
888 continue;
889 }
890 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
891 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
892 seen.getValue()) {
893 return true;
894 }
895 }
896 return false;
897 }
898
Saurav Das7bcbe702017-06-13 15:35:54 -0700899 /**
900 * Returns true if the link being queried is a bidirectional link. A bidi
901 * link is defined as a link, whose reverse link - ie. the link in the reverse
902 * direction - has been seen-before and is up. It is not necessary for the link
903 * being queried to be a seen-link.
904 *
905 * @param link the infrastructure link being queried
906 * @return true if another unidirectional link exists in the reverse direction,
907 * has been seen-before and is up
908 */
909 public boolean isBidirectional(Link link) {
910 Link reverseLink = linkService.getLink(link.dst(), link.src());
911 if (reverseLink == null) {
912 return false;
913 }
914 Boolean result = isSeenLinkUp(reverseLink);
915 if (result == null) {
916 return false;
917 }
918 return result.booleanValue();
919 }
920
921 /**
922 * Determines if the given link should be avoided in routing calculations
923 * by policy or design.
924 *
925 * @param link the infrastructure link being queried
926 * @return true if link should be avoided
927 */
928 public boolean avoidLink(Link link) {
929 // XXX currently only avoids all pair-links. In the future can be
930 // extended to avoid any generic link
931 DeviceId src = link.src().deviceId();
932 PortNumber srcPort = link.src().port();
933 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
934 log.warn("Device {} not configured..cannot avoid link {}", src, link);
935 return false;
936 }
937 DeviceId pairDev;
938 PortNumber pairLocalPort, pairRemotePort = null;
939 try {
940 pairDev = deviceConfiguration.getPairDeviceId(src);
941 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
942 if (pairDev != null) {
943 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
944 }
945 } catch (DeviceConfigNotFoundException e) {
946 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
947 src, link);
948 return false;
949 }
950
951 if (srcPort.equals(pairLocalPort) &&
952 link.dst().deviceId().equals(pairDev) &&
953 link.dst().port().equals(pairRemotePort)) {
954 return true;
955 }
956 return false;
957 }
958
sanghob35a6192015-04-01 13:05:26 -0700959 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700960 @Override
961 public void process(PacketContext context) {
962
963 if (context.isHandled()) {
964 return;
965 }
966
967 InboundPacket pkt = context.inPacket();
968 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -0800969
970 if (ethernet == null) {
971 return;
972 }
973
Saurav Das7bcbe702017-06-13 15:35:54 -0700974 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
975 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -0800976 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700977 log.warn("Received unexpected ARP packet on {}",
978 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -0700979 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -0800980 return;
sanghob35a6192015-04-01 13:05:26 -0700981 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -0800982 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
983 //ipHandler.addToPacketBuffer(ipv4Packet);
984 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
985 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700986 } else {
Charles Chan50035632017-01-13 17:20:44 -0800987 // NOTE: We don't support IP learning at this moment so this
988 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -0800989 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700990 }
Pier Ventre10bd8d12016-11-26 21:05:22 -0800991 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
992 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -0800993 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -0800994 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -0800995 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
996 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
997 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
998 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
999 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1000 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001001 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001002 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001003 }
1004 } else {
1005 // NOTE: We don't support IP learning at this moment so this
1006 // is not necessary. Also it causes duplication of DHCPv6 packets.
1007 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1008 }
sanghob35a6192015-04-01 13:05:26 -07001009 }
1010 }
1011 }
1012
1013 private class InternalLinkListener implements LinkListener {
1014 @Override
1015 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001016 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1017 event.type() == LinkEvent.Type.LINK_UPDATED ||
1018 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001019 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001020 scheduleEventHandlerIfNotScheduled(event);
1021 }
1022 }
1023 }
1024
1025 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001026 @Override
1027 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001028 switch (event.type()) {
1029 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001030 case PORT_UPDATED:
1031 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001032 case DEVICE_UPDATED:
1033 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001034 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001035 scheduleEventHandlerIfNotScheduled(event);
1036 break;
1037 default:
1038 }
1039 }
1040 }
1041
Saurav Das4ce45962015-11-24 23:21:05 -08001042 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001043 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001044 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001045 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001046 numOfEventsQueued++;
1047
1048 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1049 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001050 eventHandlerFuture = executorService
1051 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1052 numOfHandlerScheduled++;
1053 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001054 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001055 numOfEventsQueued,
1056 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001057 }
sanghob35a6192015-04-01 13:05:26 -07001058 }
1059
1060 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001061 @Override
sanghob35a6192015-04-01 13:05:26 -07001062 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001063 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001064 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -08001065 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001066 Event event;
1067 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001068 if (!eventQueue.isEmpty()) {
1069 event = eventQueue.poll();
1070 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001071 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001072 numOfHandlerExecution++;
1073 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1074 numOfHandlerExecution, numOfEventsExecuted);
1075 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001076 }
sangho20eff1d2015-04-13 15:15:58 -07001077 }
Charles Chanb1f8c762017-03-29 16:39:05 -07001078 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1079 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001080 // Note: do not update seenLinks here, otherwise every
1081 // link, even one seen for the first time, will be appear
1082 // to be a previously seen link
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001083 processLinkAdded((Link) event.subject());
1084 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -07001085 Link linkRemoved = (Link) event.subject();
Saurav Dasc88d4662017-05-15 15:34:25 -07001086 if (linkRemoved.type() == Link.Type.DIRECT) {
1087 updateSeenLink(linkRemoved, false);
1088 }
1089 // device availability check helps to ensure that
1090 // multiple link-removed events are actually treated as a
1091 // single switch removed event. purgeSeenLink is necessary
1092 // so we do rerouting (instead of rehashing) when switch
1093 // comes back.
Pier Ventre2c515312016-09-13 21:33:40 -07001094 if (linkRemoved.src().elementId() instanceof DeviceId &&
1095 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001096 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001097 continue;
1098 }
1099 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1100 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001101 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001102 continue;
1103 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001104 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001105 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1106 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1107 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001108 DeviceId deviceId = ((Device) event.subject()).id();
1109 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001110 log.info("Processing device event {} for available device {}",
1111 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001112 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001113 } else {
1114 log.info("Processing device event {} for unavailable device {}",
1115 event.type(), ((Device) event.subject()).id());
1116 processDeviceRemoved((Device) event.subject());
1117 }
Saurav Das1a129a02016-11-18 15:21:57 -08001118 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001119 // typically these calls come when device is added first time
1120 // so port filtering rules are handled at the device_added event.
1121 // port added calls represent all ports on the device,
1122 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001123 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001124 ((DeviceEvent) event).subject().id(),
1125 ((DeviceEvent) event).port().number(),
1126 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001127 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001128 // these calls happen for every subsequent event
1129 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001130 log.info("** PORT UPDATED {}/{} -> {}",
1131 event.subject(),
1132 ((DeviceEvent) event).port(),
1133 event.type());
1134 processPortUpdated(((Device) event.subject()),
1135 ((DeviceEvent) event).port());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001136 } else {
1137 log.warn("Unhandled event type: {}", event.type());
1138 }
sanghob35a6192015-04-01 13:05:26 -07001139 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001140 } catch (Exception e) {
1141 log.error("SegmentRouting event handler "
1142 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -07001143 }
sanghob35a6192015-04-01 13:05:26 -07001144 }
1145 }
1146
sanghob35a6192015-04-01 13:05:26 -07001147 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001148 log.info("** LINK ADDED {}", link.toString());
Saurav Dasc88d4662017-05-15 15:34:25 -07001149 if (link.type() != Link.Type.DIRECT) {
1150 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1151 // if BDDP is received before LLDP. We can safely ignore that
1152 // until the LLDP is received and the link is marked as DIRECT.
1153 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1154 link.src(), link.dst(), link.type());
1155 return;
1156 }
Saurav Das041bb782017-08-14 16:44:43 -07001157 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1158 updateSeenLink(link, true);
1159 // XXX revisit - what about devicePortMap
1160 log.warn("Source device of this link is not configured.. "
1161 + "not processing further");
1162 return;
1163 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001164
1165 //Irrespective of whether the local is a MASTER or not for this device,
1166 //create group handler instance and push default TTP flow rules if needed,
1167 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001168 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1169 .deviceId());
1170 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001171 groupHandler.portUpForLink(link);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001172 } else {
Saurav Das041bb782017-08-14 16:44:43 -07001173 // XXX revisit/cleanup
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001174 Device device = deviceService.getDevice(link.src().deviceId());
1175 if (device != null) {
1176 log.warn("processLinkAdded: Link Added "
1177 + "Notification without Device Added "
1178 + "event, still handling it");
1179 processDeviceAdded(device);
1180 groupHandler = groupHandlerMap.get(link.src()
1181 .deviceId());
Saurav Dasc88d4662017-05-15 15:34:25 -07001182 groupHandler.portUpForLink(link);
sanghob35a6192015-04-01 13:05:26 -07001183 }
1184 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001185
Saurav Das7bcbe702017-06-13 15:35:54 -07001186 /*// process link only if it is bidirectional
1187 if (!isBidirectional(link)) {
1188 log.debug("Link not bidirectional.. waiting for other direction "
1189 + "src {} --> dst {} ", link.dst(), link.src());
1190 // note that if we are not processing for routing, it should at least
1191 // be considered a seen-link
1192 updateSeenLink(link, true);
1193 return;
1194 }
1195 TO DO this ensure that rehash is still done correctly even if link is
1196 not processed for rerouting - perhaps rehash in both directions when
1197 it ultimately becomes bidi?
1198 */
1199
1200 log.debug("Starting optimized route population process for link "
1201 + "{} --> {}", link.src(), link.dst());
Saurav Dasc88d4662017-05-15 15:34:25 -07001202 boolean seenBefore = isSeenLink(link);
1203 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das7bcbe702017-06-13 15:35:54 -07001204
1205 // It's possible that linkUp causes no route-path change as ECMP graph does
1206 // not change if the link is a parallel link (same src-dst as another link.
1207 // However we still need to update ECMP hash groups to include new buckets
1208 // for the link that has come up.
Saurav Dasc88d4662017-05-15 15:34:25 -07001209 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001210 if (!seenBefore && isParallelLink(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001211 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das7bcbe702017-06-13 15:35:54 -07001212 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001213 groupHandler.retryHash(link, false, true);
1214 } else {
1215 //seen before-link
1216 if (isParallelLink(link)) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001217 log.debug("Attempting retryHash for paralled seen-before "
1218 + "link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001219 groupHandler.retryHash(link, false, false);
1220 }
1221 }
1222 }
Charles Chan2199c302016-04-23 17:36:10 -07001223
1224 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -07001225 }
1226
1227 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001228 log.info("** LINK REMOVED {}", link.toString());
Saurav Dasc88d4662017-05-15 15:34:25 -07001229 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1230
1231 // update local groupHandler stores
sangho834e4b02015-05-01 09:38:25 -07001232 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1233 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001234 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1235 isParallelLink(link)) {
Saurav Das041bb782017-08-14 16:44:43 -07001236 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001237 groupHandler.retryHash(link, true, false);
Saurav Das041bb782017-08-14 16:44:43 -07001238 } else {
1239 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1240 (mastershipService.isLocalMaster(link.src().deviceId()))
1241 ? "not parallel" : "not master");
Saurav Dasc88d4662017-05-15 15:34:25 -07001242 }
1243 // ensure local stores are updated
1244 groupHandler.portDown(link.src().port());
1245 } else {
1246 log.warn("group handler not found for dev:{} when removing link: {}",
1247 link.src().deviceId(), link);
sangho834e4b02015-05-01 09:38:25 -07001248 }
Charles Chan2199c302016-04-23 17:36:10 -07001249
1250 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -07001251 }
1252
1253 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001254 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001255
1256 // NOTE: Punt ARP/NDP even when the device is not configured.
1257 // Host learning without network config is required for CORD config generator.
1258 routingRulePopulator.populateIpPunts(device.id());
1259 routingRulePopulator.populateArpNdpPunts(device.id());
1260
Charles Chan0b4e6182015-11-03 10:42:14 -08001261 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001262 log.warn("Device configuration unavailable. Device {} will be "
1263 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001264 return;
1265 }
Charles Chan2199c302016-04-23 17:36:10 -07001266 processDeviceAddedInternal(device.id());
1267 }
1268
1269 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001270 // Irrespective of whether the local is a MASTER or not for this device,
1271 // we need to create a SR-group-handler instance. This is because in a
1272 // multi-instance setup, any instance can initiate forwarding/next-objectives
1273 // for any switch (even if this instance is a SLAVE or not even connected
1274 // to the switch). To handle this, a default-group-handler instance is necessary
1275 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001276 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1277 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001278 DefaultGroupHandler groupHandler;
1279 try {
1280 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001281 createGroupHandler(deviceId,
1282 appId,
1283 deviceConfiguration,
1284 linkService,
1285 flowObjectiveService,
1286 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001287 } catch (DeviceConfigNotFoundException e) {
1288 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1289 return;
1290 }
Saurav Das9aa28bd2017-12-05 15:00:23 -08001291 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001292 deviceId);
1293 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001294 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001295
Charles Chan2199c302016-04-23 17:36:10 -07001296 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001297 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001298 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001299 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001300 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001301 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001302 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001303 }
Charles Chan5270ed02016-01-30 23:22:37 -08001304
Charles Chan03a73e02016-10-24 14:52:01 -07001305 appCfgHandler.init(deviceId);
1306 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001307 }
1308
Saurav Das80980c72016-03-23 11:22:49 -07001309 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001310 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001311 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1312 .forEach(entry -> {
Saurav Das7bcbe702017-06-13 15:35:54 -07001313 dsNextObjStore.remove(entry.getKey());
Saurav Das80980c72016-03-23 11:22:49 -07001314 });
Charles Chan59cc16d2017-02-02 16:20:42 -08001315 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001316 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001317 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001318 portNextObjStore.entrySet().stream()
1319 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001320 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chaned3742352017-06-15 00:44:51 -07001321
1322 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1323 key.dst().deviceId().equals(device.id()));
1324
Saurav Dasceccf242017-08-03 18:30:35 -07001325 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1326 if (gh != null) {
1327 gh.shutdown();
1328 }
Saurav Das80980c72016-03-23 11:22:49 -07001329 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Dasc88d4662017-05-15 15:34:25 -07001330 // Note that a switch going down is associated with all of its links
1331 // going down as well, but it is treated as a single switch down event
1332 // while the link-downs are ignored.
1333 defaultRoutingHandler
1334 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan2199c302016-04-23 17:36:10 -07001335 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001336 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -07001337 }
1338
Saurav Das1a129a02016-11-18 15:21:57 -08001339 private void processPortUpdated(Device device, Port port) {
1340 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1341 log.warn("Device configuration uploading. Not handling port event for"
1342 + "dev: {} port: {}", device.id(), port.number());
1343 return;
1344 }
Saurav Das018605f2017-02-18 14:05:44 -08001345
1346 if (!mastershipService.isLocalMaster(device.id())) {
1347 log.debug("Not master for dev:{} .. not handling port updated event"
1348 + "for port {}", device.id(), port.number());
1349 return;
1350 }
1351
1352 // first we handle filtering rules associated with the port
1353 if (port.isEnabled()) {
1354 log.info("Switchport {}/{} enabled..programming filters",
1355 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001356 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001357 } else {
1358 log.info("Switchport {}/{} disabled..removing filters",
1359 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001360 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001361 }
Saurav Das1a129a02016-11-18 15:21:57 -08001362
1363 // portUpdated calls are for ports that have gone down or up. For switch
1364 // to switch ports, link-events should take care of any re-routing or
1365 // group editing necessary for port up/down. Here we only process edge ports
1366 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001367 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1368 VlanId untaggedVlan = getUntaggedVlanId(cp);
1369 VlanId nativeVlan = getNativeVlanId(cp);
1370 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001371
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001372 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001373 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001374 + "dev/port: {}/{}", device.id(), port.number());
1375 return;
1376 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001377 if (untaggedVlan != null) {
1378 processEdgePort(device, port, untaggedVlan, true);
1379 }
1380 if (nativeVlan != null) {
1381 processEdgePort(device, port, nativeVlan, true);
1382 }
1383 if (!taggedVlans.isEmpty()) {
1384 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1385 }
Saurav Das1a129a02016-11-18 15:21:57 -08001386 }
1387
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001388 private void processEdgePort(Device device, Port port, VlanId vlanId,
1389 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001390 boolean portUp = port.isEnabled();
1391 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001392 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001393 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001394 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001395 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001396 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001397 }
1398
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001399 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001400 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001401 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001402 } else {
1403 log.warn("Group handler not found for dev:{}. Not handling edge port"
1404 + " {} event for port:{}", device.id(),
1405 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001406 }
1407 }
sangho1e575652015-05-14 00:39:53 -07001408
Charles Chan463c6442017-10-20 16:06:55 -07001409 private void createOrUpdateDeviceConfiguration() {
1410 if (deviceConfiguration == null) {
1411 deviceConfiguration = new DeviceConfiguration(this);
1412 } else {
1413 deviceConfiguration.updateConfig();
1414 }
1415 }
1416
Pier Ventre10bd8d12016-11-26 21:05:22 -08001417 /**
1418 * Registers the given connect point with the NRS, this is necessary
1419 * to receive the NDP and ARP packets from the NRS.
1420 *
1421 * @param portToRegister connect point to register
1422 */
1423 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001424 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001425 portToRegister,
1426 neighbourHandler,
1427 appId
1428 );
1429 }
1430
Charles Chand6832882015-10-05 17:50:33 -07001431 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001432 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001433 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001434
Charles Chane849c192016-01-11 18:28:54 -08001435 /**
1436 * Constructs the internal network config listener.
1437 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001438 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001439 */
Charles Chan65238242017-06-22 18:03:14 -07001440 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001441 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001442 }
1443
Charles Chane849c192016-01-11 18:28:54 -08001444 /**
1445 * Reads network config and initializes related data structure accordingly.
1446 */
Charles Chan4636be02015-10-07 14:21:45 -07001447 public void configureNetwork() {
Charles Chan463c6442017-10-20 16:06:55 -07001448 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001449
Charles Chan2c15aca2016-11-09 20:51:44 -08001450 arpHandler = new ArpHandler(srManager);
1451 icmpHandler = new IcmpHandler(srManager);
1452 ipHandler = new IpHandler(srManager);
1453 routingRulePopulator = new RoutingRulePopulator(srManager);
1454 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001455
1456 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1457 groupHandlerMap, tunnelStore);
1458 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1459 flowObjectiveService,
1460 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001461 // add a small delay to absorb multiple network config added notifications
1462 if (!programmingScheduled.get()) {
1463 programmingScheduled.set(true);
1464 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1465 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001466 }
Charles Chan2199c302016-04-23 17:36:10 -07001467 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001468 }
1469
Charles Chand6832882015-10-05 17:50:33 -07001470 @Override
1471 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001472 // TODO move this part to NetworkConfigEventHandler
1473 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1474 switch (event.type()) {
1475 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001476 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001477 configureNetwork();
1478 break;
1479 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001480 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001481 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001482 // TODO support dynamic configuration
1483 break;
1484 default:
1485 break;
1486 }
1487 } else if (event.configClass().equals(InterfaceConfig.class)) {
1488 switch (event.type()) {
1489 case CONFIG_ADDED:
1490 log.info("Interface Config added for {}", event.subject());
1491 configureNetwork();
1492 break;
1493 case CONFIG_UPDATED:
1494 log.info("Interface Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001495 createOrUpdateDeviceConfiguration();
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001496
1497 // Following code will be uncommented when [CORD-634] is fully implemented.
1498 // [CORD-634] Add dynamic config support for interfaces
1499 updateInterface((InterfaceConfig) event.config().get(),
1500 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001501 // TODO support dynamic configuration
1502 break;
1503 default:
1504 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001505 }
Charles Chan5270ed02016-01-30 23:22:37 -08001506 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001507 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001508 switch (event.type()) {
1509 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001510 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001511 break;
1512 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001513 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001514 break;
1515 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001516 appCfgHandler.processAppConfigRemoved(event);
1517 break;
1518 default:
1519 break;
1520 }
Charles Chan03a73e02016-10-24 14:52:01 -07001521 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001522 } else if (event.configClass().equals(XConnectConfig.class)) {
1523 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1524 switch (event.type()) {
1525 case CONFIG_ADDED:
1526 xConnectHandler.processXConnectConfigAdded(event);
1527 break;
1528 case CONFIG_UPDATED:
1529 xConnectHandler.processXConnectConfigUpdated(event);
1530 break;
1531 case CONFIG_REMOVED:
1532 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001533 break;
1534 default:
1535 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001536 }
Pier Ventref34966c2016-11-07 16:21:04 -08001537 } else if (event.configClass().equals(PwaasConfig.class)) {
1538 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1539 switch (event.type()) {
1540 case CONFIG_ADDED:
1541 l2TunnelHandler.processPwaasConfigAdded(event);
1542 break;
1543 case CONFIG_UPDATED:
1544 l2TunnelHandler.processPwaasConfigUpdated(event);
1545 break;
1546 case CONFIG_REMOVED:
1547 l2TunnelHandler.processPwaasConfigRemoved(event);
1548 break;
1549 default:
1550 break;
1551 }
Charles Chand6832882015-10-05 17:50:33 -07001552 }
1553 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001554
1555 private final class ConfigChange implements Runnable {
1556 @Override
1557 public void run() {
1558 programmingScheduled.set(false);
1559 for (Device device : deviceService.getDevices()) {
1560 processDeviceAdded(device);
1561 }
1562 defaultRoutingHandler.startPopulationProcess();
1563 }
1564 }
Charles Chand6832882015-10-05 17:50:33 -07001565 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001566
1567 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001568 @Override
1569 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001570 switch (event.type()) {
1571 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001572 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001573 break;
1574 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001575 hostHandler.processHostMovedEvent(event);
Charles Chan23686832017-08-23 14:46:43 -07001576 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001577 break;
1578 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001579 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001580 break;
1581 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001582 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001583 break;
1584 default:
1585 log.warn("Unsupported host event type: {}", event.type());
1586 break;
1587 }
1588 }
1589 }
1590
Charles Chand55e84d2016-03-30 17:54:24 -07001591 private class InternalMcastListener implements McastListener {
1592 @Override
1593 public void event(McastEvent event) {
1594 switch (event.type()) {
1595 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001596 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001597 break;
1598 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001599 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001600 break;
1601 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001602 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001603 break;
1604 case ROUTE_ADDED:
1605 case ROUTE_REMOVED:
1606 default:
1607 break;
1608 }
1609 }
1610 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001611
Charles Chan03a73e02016-10-24 14:52:01 -07001612 private class InternalRouteEventListener implements RouteListener {
1613 @Override
1614 public void event(RouteEvent event) {
1615 switch (event.type()) {
1616 case ROUTE_ADDED:
1617 routeHandler.processRouteAdded(event);
1618 break;
1619 case ROUTE_UPDATED:
1620 routeHandler.processRouteUpdated(event);
1621 break;
1622 case ROUTE_REMOVED:
1623 routeHandler.processRouteRemoved(event);
1624 break;
Charles Chan23686832017-08-23 14:46:43 -07001625 case ALTERNATIVE_ROUTES_CHANGED:
1626 routeHandler.processAlternativeRoutesChanged(event);
1627 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001628 default:
1629 break;
1630 }
1631 }
1632 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001633
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001634 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1635 try {
1636 Set<Interface> intfs = conf.getInterfaces();
1637 Set<Interface> prevIntfs = prevConf.getInterfaces();
1638
1639 // Now we only handle one interface config at each port.
1640 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1641 log.warn("Interface update aborted - one at a time is allowed, " +
1642 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1643 return;
1644 }
1645
1646 Interface intf = intfs.stream().findFirst().get();
1647 Interface prevIntf = prevIntfs.stream().findFirst().get();
1648
1649 DeviceId deviceId = intf.connectPoint().deviceId();
1650 PortNumber portNum = intf.connectPoint().port();
1651
1652 if (!mastershipService.isLocalMaster(deviceId)) {
1653 log.debug("CONFIG_UPDATED event for interfaces should be " +
1654 "handled by master node for device {}", deviceId);
1655 return;
1656 }
1657
1658 removeSubnetConfig(prevIntf.connectPoint(),
1659 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1660 new HashSet<>(intf.ipAddressesList())));
1661
1662 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1663 // RemoveVlanNative
1664 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1665 }
1666
1667 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1668 // RemoveVlanTagged
1669 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1670 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1671 );
1672 }
1673
1674 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1675 // RemoveVlanUntagged
1676 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1677 }
1678
1679 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1680 // AddVlanNative
1681 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1682 }
1683
1684 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1685 // AddVlanTagged
1686 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1687 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1688 );
1689 }
1690
1691 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1692 // AddVlanUntagged
1693 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1694 }
1695 addSubnetConfig(prevIntf.connectPoint(),
1696 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1697 new HashSet<>(prevIntf.ipAddressesList())));
1698 } catch (ConfigException e) {
1699 log.error("Error in configuration");
1700 }
1701 }
1702
1703 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1704 VlanId vlanId, boolean pushVlan, boolean install) {
1705 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1706 if (grpHandler == null) {
1707 log.warn("Failed to retrieve group handler for device {}", deviceId);
1708 return;
1709 }
1710
1711 // Update filtering objective for a single port
1712 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1713
1714 // Update filtering objective for multicast ingress port
1715 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1716
1717 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1718
1719 if (nextId != -1 && !install) {
1720 // Update next objective for a single port as an output port
1721 // Remove a single port from L2FG
1722 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1723 // Remove L2 Bridging rule and L3 Unicast rule to the host
1724 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1725 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1726 // only if there is no port configured on that VLAN ID
1727 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1728 // Remove broadcast forwarding rule for the VLAN
1729 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1730 // Remove L2FG for VLAN
1731 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1732 } else {
1733 // Remove L2IG of the port
1734 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1735 }
1736 } else if (install) {
1737 if (nextId != -1) {
1738 // Add a single port to L2FG
1739 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1740 } else {
1741 // Create L2FG for VLAN
1742 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1743 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1744 }
1745 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1746 } else {
1747 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1748 }
1749 }
1750
1751 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1752 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1753 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1754
1755 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1756 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1757 .filter(intf -> !intf.connectPoint().equals(cp))
1758 .flatMap(intf -> intf.ipAddressesList().stream())
1759 .collect(Collectors.toSet());
1760 // 1. Partial subnet population
1761 // Remove routing rules for removed subnet from previous configuration,
1762 // which does not also exist in other interfaces in the same device
1763 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1764 .map(InterfaceIpAddress::subnetAddress)
1765 .collect(Collectors.toSet());
1766
1767 defaultRoutingHandler.revokeSubnet(
1768 ipPrefixSet.stream()
1769 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1770 .collect(Collectors.toSet()));
1771
1772 // 2. Interface IP punts
1773 // Remove IP punts for old Intf address
1774 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1775 .map(InterfaceIpAddress::ipAddress)
1776 .collect(Collectors.toSet());
1777 ipAddressSet.stream()
1778 .map(InterfaceIpAddress::ipAddress)
1779 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1780 .forEach(interfaceIpAddress ->
1781 routingRulePopulator.revokeSingleIpPunts(
1782 cp.deviceId(), interfaceIpAddress));
1783
1784 // 3. Host unicast routing rule
1785 // Remove unicast routing rule
1786 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1787 }
1788
1789 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1790 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1791 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1792
1793 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1794 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1795 .filter(intf -> !intf.connectPoint().equals(cp))
1796 .flatMap(intf -> intf.ipAddressesList().stream())
1797 .collect(Collectors.toSet());
1798 // 1. Partial subnet population
1799 // Add routing rules for newly added subnet, which does not also exist in
1800 // other interfaces in the same device
1801 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1802 .map(InterfaceIpAddress::subnetAddress)
1803 .collect(Collectors.toSet());
1804
1805 defaultRoutingHandler.populateSubnet(
1806 Collections.singleton(cp),
1807 ipPrefixSet.stream()
1808 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1809 .collect(Collectors.toSet()));
1810
1811 // 2. Interface IP punts
1812 // Add IP punts for new Intf address
1813 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1814 .map(InterfaceIpAddress::ipAddress)
1815 .collect(Collectors.toSet());
1816 ipAddressSet.stream()
1817 .map(InterfaceIpAddress::ipAddress)
1818 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1819 .forEach(interfaceIpAddress ->
1820 routingRulePopulator.populateSingleIpPunts(
1821 cp.deviceId(), interfaceIpAddress));
1822
1823 // 3. Host unicast routing rule
1824 // Add unicast routing rule
1825 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1826 }
sanghob35a6192015-04-01 13:05:26 -07001827}