blob: 954417288908cdbfa1c95781e11adce173d9cb83 [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
Jonathan Hart8ca2bc02017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chan9640c812017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
Charles Chan47933752017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sanghob35a6192015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan47933752017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Das80980c72016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Pier Luigieba73a02018-01-16 10:47:50 +010041import org.onosproject.cluster.ClusterService;
42import org.onosproject.cluster.LeadershipService;
sanghob35a6192015-04-01 13:05:26 -070043import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070046import org.onosproject.mastership.MastershipService;
Pier3ee24552018-03-14 16:47:32 -070047import org.onosproject.mcast.api.McastEvent;
48import org.onosproject.mcast.api.McastListener;
49import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080050import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070051import org.onosproject.net.Device;
52import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070053import org.onosproject.net.Host;
54import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070055import org.onosproject.net.Link;
56import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080057import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070058import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070059import org.onosproject.net.config.ConfigFactory;
60import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070061import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070062import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070063import org.onosproject.net.config.basics.InterfaceConfig;
64import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070065import org.onosproject.net.config.basics.SubjectFactories;
Saurav Das45f48152018-01-18 12:07:33 -080066import org.onosproject.net.device.DeviceAdminService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070067import org.onosproject.net.device.DeviceEvent;
68import org.onosproject.net.device.DeviceListener;
69import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080070import org.onosproject.net.flow.TrafficSelector;
71import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070072import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080073import org.onosproject.net.host.HostEvent;
74import org.onosproject.net.host.HostListener;
Charles Chan47933752017-11-30 15:37:50 -080075import org.onosproject.net.host.HostLocationProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080076import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070077import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070078import org.onosproject.net.intf.Interface;
79import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080080import org.onosproject.net.link.LinkEvent;
81import org.onosproject.net.link.LinkListener;
82import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
96import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -080097import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070098import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070099import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700101import org.onosproject.segmentrouting.grouphandler.DestinationSet;
102import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100103import org.onosproject.segmentrouting.mcast.McastHandler;
104import org.onosproject.segmentrouting.mcast.McastRole;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700105import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700106import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800109
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800112import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
114
Saurav Das7bcbe702017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigib29144d2018-01-15 18:06:43 +0100116import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700120import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700121import org.onosproject.store.service.EventuallyConsistentMap;
122import org.onosproject.store.service.EventuallyConsistentMapBuilder;
123import org.onosproject.store.service.StorageService;
124import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800125import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700126import org.slf4j.Logger;
127import org.slf4j.LoggerFactory;
128
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700129import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800130import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800131import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800132import java.util.HashSet;
133import java.util.List;
134import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800135import java.util.Optional;
136import java.util.Set;
137import java.util.concurrent.ConcurrentHashMap;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800138import java.util.concurrent.Executors;
139import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800140import java.util.concurrent.TimeUnit;
141import java.util.concurrent.atomic.AtomicBoolean;
142import java.util.stream.Collectors;
sanghob35a6192015-04-01 13:05:26 -0700143
Charles Chan3e783d02016-02-26 22:19:52 -0800144import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800145import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700146import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800147import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
148import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800149
Charles Chane849c192016-01-11 18:28:54 -0800150/**
151 * Segment routing manager.
152 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700153@Service
154@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700155public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700156
Charles Chan2c15aca2016-11-09 20:51:44 -0800157 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700158 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700161 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800164 private NeighbourResolutionService neighbourResolutionService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100167 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700170 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700173 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan47933752017-11-30 15:37:50 -0800176 HostLocationProbingService probingService;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100179 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800182 DeviceAdminService deviceAdminService;
183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800185 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100188 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700189
Charles Chan5270ed02016-01-30 23:22:37 -0800190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800191 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800194 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100197 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800200 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700203 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800204
205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800206 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800207
Saurav Das80980c72016-03-23 11:22:49 -0700208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800209 public InterfaceService interfaceService;
210
Pier Luigieba73a02018-01-16 10:47:50 +0100211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
212 public ClusterService clusterService;
213
214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
215 public LeadershipService leadershipService;
216
Charles Chan47933752017-11-30 15:37:50 -0800217 @Property(name = "activeProbing", boolValue = true,
218 label = "Enable active probing to discover dual-homed hosts.")
219 boolean activeProbing = true;
220
Charles Chan03a73e02016-10-24 14:52:01 -0700221 ArpHandler arpHandler = null;
222 IcmpHandler icmpHandler = null;
223 IpHandler ipHandler = null;
224 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700225 ApplicationId appId;
226 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700227
Charles Chan03a73e02016-10-24 14:52:01 -0700228 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700229 private TunnelHandler tunnelHandler = null;
230 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700231 private InternalPacketProcessor processor = null;
232 private InternalLinkListener linkListener = null;
233 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700234 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100235 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800236 McastHandler mcastHandler = null;
237 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800238 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800239 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800240 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800241 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100242 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800243 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700244 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
245 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700246 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100247 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sanghob35a6192015-04-01 13:05:26 -0700248
Charles Chan9b7217c2018-04-05 16:31:15 -0700249 // Handles device, link, topology and network config events
250 private ScheduledExecutorService mainEventExecutor = Executors
251 .newScheduledThreadPool(1, groupedThreads("sr-event-main", "%d", log));
sanghob35a6192015-04-01 13:05:26 -0700252
Charles Chan9b7217c2018-04-05 16:31:15 -0700253 // Handles host, route, mcast events
254 private ScheduledExecutorService hostEventExecutor = Executors
255 .newScheduledThreadPool(1, groupedThreads("sr-event-host", "%d", log));
256 private ScheduledExecutorService routeEventExecutor = Executors
257 .newScheduledThreadPool(1, groupedThreads("sr-event-route", "%d", log));
258 private ScheduledExecutorService mcastEventExecutor = Executors
259 .newScheduledThreadPool(1, groupedThreads("sr-event-mcast", "%d", log));
260
261
262 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800263 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700264 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700265 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800266 */
Charles Chan47933752017-11-30 15:37:50 -0800267 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700268 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800269 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700270 * Per device next objective ID store with (device id + vlanid) as key.
271 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800272 */
Charles Chan47933752017-11-30 15:37:50 -0800273 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800274 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800275 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700276 * Per device next objective ID store with (device id + port + treatment + meta) as key.
277 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800278 */
Charles Chan47933752017-11-30 15:37:50 -0800279 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800280 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800281
Saurav Das4ce45962015-11-24 23:21:05 -0800282 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
283 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700284
Saurav Das7bcbe702017-06-13 15:35:54 -0700285 private AtomicBoolean programmingScheduled = new AtomicBoolean();
286
Charles Chand55e84d2016-03-30 17:54:24 -0700287 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700288 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
289 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700290 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700291 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800292 public SegmentRoutingDeviceConfig createConfig() {
293 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700294 }
295 };
Pier Ventref34966c2016-11-07 16:21:04 -0800296
Charles Chand55e84d2016-03-30 17:54:24 -0700297 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700298 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
299 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700300 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800301 @Override
302 public SegmentRoutingAppConfig createConfig() {
303 return new SegmentRoutingAppConfig();
304 }
305 };
Pier Ventref34966c2016-11-07 16:21:04 -0800306
Charles Chanfc5c7802016-05-17 13:13:55 -0700307 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
308 new ConfigFactory<ApplicationId, XConnectConfig>(
309 SubjectFactories.APP_SUBJECT_FACTORY,
310 XConnectConfig.class, "xconnect") {
311 @Override
312 public XConnectConfig createConfig() {
313 return new XConnectConfig();
314 }
315 };
Pier Ventref34966c2016-11-07 16:21:04 -0800316
Charles Chand55e84d2016-03-30 17:54:24 -0700317 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700318 new ConfigFactory<ApplicationId, McastConfig>(
319 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700320 McastConfig.class, "multicast") {
321 @Override
322 public McastConfig createConfig() {
323 return new McastConfig();
324 }
325 };
326
Charles Chan65238242017-06-22 18:03:14 -0700327 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700328 private static int numOfEventsQueued = 0;
329 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700330 private static int numOfHandlerExecution = 0;
331 private static int numOfHandlerScheduled = 0;
332
Charles Chan116188d2016-02-18 14:22:42 -0800333 /**
334 * Segment Routing App ID.
335 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800336 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800337
Charles Chane849c192016-01-11 18:28:54 -0800338 /**
339 * The default VLAN ID assigned to the interfaces without subnet config.
340 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800341 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700342
sanghob35a6192015-04-01 13:05:26 -0700343 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800344 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800345 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700346
347 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700348 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700349 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700350 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700351 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700352 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700353 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700354 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700355 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700356
Charles Chan59cc16d2017-02-02 16:20:42 -0800357 log.debug("Creating EC map vlannextobjectivestore");
358 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
359 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
360 vlanNextObjStore = vlanNextObjMapBuilder
361 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700362 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700363 .withTimestampProvider((k, v) -> new WallClockTimestamp())
364 .build();
365
Saurav Das4ce45962015-11-24 23:21:05 -0800366 log.debug("Creating EC map subnetnextobjectivestore");
367 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
368 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
369 portNextObjStore = portNextObjMapBuilder
370 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700371 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800372 .withTimestampProvider((k, v) -> new WallClockTimestamp())
373 .build();
374
sangho0b2b6d12015-05-20 22:16:38 -0700375 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
376 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700377 tunnelStore = tunnelMapBuilder
378 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700379 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700380 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700381 .build();
382
383 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
384 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700385 policyStore = policyMapBuilder
386 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700387 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700388 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700389 .build();
390
Saurav Das80980c72016-03-23 11:22:49 -0700391 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800392 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700393 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800394 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800395 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
396 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700397 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800398 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700399 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800400 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800401 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
402 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800403 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
404 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700405 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700406 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700407 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
408 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800409 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
410 "staleLinkAge", "15000");
411 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
412 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800413 compCfgService.registerProperties(getClass());
414 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700415
Charles Chanb8e10c82015-10-14 11:24:40 -0700416 processor = new InternalPacketProcessor();
417 linkListener = new InternalLinkListener();
418 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700419 appCfgHandler = new AppConfigHandler(this);
420 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700421 mcastHandler = new McastHandler(this);
422 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800423 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700424 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800425 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800426 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100427 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700428
Charles Chan3e783d02016-02-26 22:19:52 -0800429 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700430 cfgService.registerConfigFactory(deviceConfigFactory);
431 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700432 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700433 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800434 log.info("Configuring network before adding listeners");
Charles Chan132393a2018-01-04 14:26:07 -0800435 cfgListener.configureNetwork();
436
Charles Chan5270ed02016-01-30 23:22:37 -0800437 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700438 packetService.addProcessor(processor, PacketProcessor.director(2));
439 linkService.addListener(linkListener);
440 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700441 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700442 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100443 topologyService.addListener(topologyListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700444
Charles Chanb39777c2018-03-09 15:53:44 -0800445 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800446 l2TunnelHandler.init();
447
sanghob35a6192015-04-01 13:05:26 -0700448 log.info("Started");
449 }
450
Saurav Das45f48152018-01-18 12:07:33 -0800451 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700452 return new KryoNamespace.Builder()
453 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700454 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800455 VlanNextObjectiveStoreKey.class,
456 DestinationSet.class,
457 NextNeighbors.class,
458 Tunnel.class,
459 DefaultTunnel.class,
460 Policy.class,
461 TunnelPolicy.class,
462 Policy.Type.class,
463 PortNextObjectiveStoreKey.class,
464 XConnectStoreKey.class,
465 L2Tunnel.class,
466 L2TunnelPolicy.class,
467 DefaultL2Tunnel.class,
468 DefaultL2TunnelPolicy.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700469 );
470 }
471
sanghob35a6192015-04-01 13:05:26 -0700472 @Deactivate
473 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700474 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700475 cfgService.unregisterConfigFactory(deviceConfigFactory);
476 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700477 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700478 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800479 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700480
Charles Chanc7a8a682017-06-19 00:43:31 -0700481 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700482 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700483 linkService.removeListener(linkListener);
484 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700485 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700486 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100487 topologyService.removeListener(topologyListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700488
Charles Chan0aa674e2017-02-23 15:44:08 -0800489 neighbourResolutionService.unregisterNeighbourHandlers(appId);
490
sanghob35a6192015-04-01 13:05:26 -0700491 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700492 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700493 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700494 groupHandlerMap.clear();
495
Saurav Das7bcbe702017-06-13 15:35:54 -0700496 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800497 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700498 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700499 tunnelStore.destroy();
500 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100501
502 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700503 log.info("Stopped");
504 }
505
Charles Chan47933752017-11-30 15:37:50 -0800506 @Modified
507 private void modified(ComponentContext context) {
508 Dictionary<?, ?> properties = context.getProperties();
509 if (properties == null) {
510 return;
511 }
512
513 String strActiveProving = Tools.get(properties, "activeProbing");
514 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
515
516 if (expectActiveProbing != activeProbing) {
517 activeProbing = expectActiveProbing;
518 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
519 }
520 }
521
sangho1e575652015-05-14 00:39:53 -0700522 @Override
523 public List<Tunnel> getTunnels() {
524 return tunnelHandler.getTunnels();
525 }
526
527 @Override
sangho71abe1b2015-06-29 14:58:47 -0700528 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
529 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700530 }
531
532 @Override
sangho71abe1b2015-06-29 14:58:47 -0700533 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700534 for (Policy policy: policyHandler.getPolicies()) {
535 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
536 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
537 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
538 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700539 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700540 }
541 }
542 }
sangho71abe1b2015-06-29 14:58:47 -0700543 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700544 }
545
546 @Override
sangho71abe1b2015-06-29 14:58:47 -0700547 public PolicyHandler.Result removePolicy(Policy policy) {
548 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700549 }
550
551 @Override
sangho71abe1b2015-06-29 14:58:47 -0700552 public PolicyHandler.Result createPolicy(Policy policy) {
553 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700554 }
555
556 @Override
557 public List<Policy> getPolicies() {
558 return policyHandler.getPolicies();
559 }
560
Saurav Das59232cf2016-04-27 18:35:50 -0700561 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700562 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
563 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700564 }
565
566 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800567 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700568 return l2TunnelHandler.getL2Tunnels();
569 }
570
571 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800572 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700573 return l2TunnelHandler.getL2Policies();
574 }
575
Saurav Das5a356042018-04-06 20:16:01 -0700576 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700577 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700578 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
579
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700580 // get both added and pending pseudowires
581 List<L2TunnelDescription> pseudowires = new ArrayList<>();
582 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
583 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700584 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700585
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700586 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
587
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700588 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
589 L2TunnelHandler.Result res;
590 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
591 res = addPseudowire(pw);
592 if (res != L2TunnelHandler.Result.SUCCESS) {
593 log.error("Pseudowire with id {} can not be instantiated !", res);
594 retRes = res;
595 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700596 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700597
598 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700599 }
600
601 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800602 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700603 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700604 }
605
606 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800607 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700608 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700609 }
610
611 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700612 public void rerouteNetwork() {
613 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700614 }
615
Charles Chanc81c45b2016-10-20 17:02:44 -0700616 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800617 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
618 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800619 deviceConfiguration.getRouters().forEach(device ->
620 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700621 return deviceSubnetMap;
622 }
623
Saurav Dasc88d4662017-05-15 15:34:25 -0700624
625 @Override
626 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
627 if (defaultRoutingHandler != null) {
628 return defaultRoutingHandler.getCurrentEmcpSpgMap();
629 } else {
630 return null;
631 }
632 }
633
634 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700635 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
636 if (dsNextObjStore != null) {
637 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700638 } else {
639 return ImmutableMap.of();
640 }
641 }
642
Saurav Dasceccf242017-08-03 18:30:35 -0700643 @Override
644 public void verifyGroups(DeviceId id) {
645 DefaultGroupHandler gh = groupHandlerMap.get(id);
646 if (gh != null) {
647 gh.triggerBucketCorrector();
648 }
649 }
650
Saurav Dasc568c342018-01-25 09:49:01 -0800651 @Override
652 public ImmutableMap<Link, Boolean> getSeenLinks() {
653 return linkHandler.getSeenLinks();
654 }
655
656 @Override
657 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
658 return linkHandler.getDownedPorts();
659 }
660
Pier Luigib29144d2018-01-15 18:06:43 +0100661 @Override
662 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
663 return mcastHandler.getMcastNextIds(mcastIp);
664 }
665
666 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100667 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100668 return mcastHandler.getMcastRoles(mcastIp);
669 }
670
671 @Override
672 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
673 return mcastHandler.getMcastPaths(mcastIp);
674 }
675
sanghof9d0bf12015-05-19 11:57:42 -0700676 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700677 * Extracts the application ID from the manager.
678 *
679 * @return application ID
680 */
681 public ApplicationId appId() {
682 return appId;
683 }
684
685 /**
686 * Returns the device configuration.
687 *
688 * @return device configuration
689 */
690 public DeviceConfiguration deviceConfiguration() {
691 return deviceConfiguration;
692 }
693
694 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700695 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700696 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700697 *
698 * @return next objective ID store
699 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700700 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
701 dsNextObjStore() {
702 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700703 }
704
705 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700706 * Per device next objective ID store with (device id + vlanid) as key.
707 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700708 *
709 * @return vlan next object store
710 */
711 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
712 return vlanNextObjStore;
713 }
714
715 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700716 * Per device next objective ID store with (device id + port + treatment + meta) as key.
717 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700718 *
719 * @return port next object store.
720 */
721 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
722 return portNextObjStore;
723 }
724
725 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700726 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
727 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700728 *
729 * @return MPLS-ECMP value
730 */
731 public boolean getMplsEcmp() {
732 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
733 .getConfig(this.appId, SegmentRoutingAppConfig.class);
734 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
735 }
736
737 /**
sanghof9d0bf12015-05-19 11:57:42 -0700738 * Returns the tunnel object with the tunnel ID.
739 *
740 * @param tunnelId Tunnel ID
741 * @return Tunnel reference
742 */
sangho1e575652015-05-14 00:39:53 -0700743 public Tunnel getTunnel(String tunnelId) {
744 return tunnelHandler.getTunnel(tunnelId);
745 }
746
Charles Chan7ffd81f2017-02-08 15:52:08 -0800747 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700748 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800749 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800750 * <p>
751 * Only returns the first match if there are multiple untagged VLAN configured
752 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700753 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800754 * @param connectPoint connect point
755 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700756 */
Charles Chan65238242017-06-22 18:03:14 -0700757 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800758 return interfaceService.getInterfacesByPort(connectPoint).stream()
759 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
760 .map(Interface::vlanUntagged)
761 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700762 }
763
sangho1e575652015-05-14 00:39:53 -0700764 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800765 * Returns tagged VLAN configured on given connect point.
766 * <p>
767 * Returns all matches if there are multiple tagged VLAN configured
768 * on the connect point.
769 *
770 * @param connectPoint connect point
771 * @return tagged VLAN or empty set if not configured
772 */
Charles Chan65238242017-06-22 18:03:14 -0700773 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800774 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
775 return interfaces.stream()
776 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700777 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800778 .collect(Collectors.toSet());
779 }
780
781 /**
782 * Returns native VLAN configured on given connect point.
783 * <p>
784 * Only returns the first match if there are multiple native VLAN configured
785 * on the connect point.
786 *
787 * @param connectPoint connect point
788 * @return native VLAN or null if not configured
789 */
Charles Chan65238242017-06-22 18:03:14 -0700790 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800791 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
792 return interfaces.stream()
793 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
794 .map(Interface::vlanNative)
795 .findFirst()
796 .orElse(null);
797 }
798
799 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700800 * Returns internal VLAN for untagged hosts on given connect point.
801 * <p>
802 * The internal VLAN is either vlan-untagged for an access port,
803 * or vlan-native for a trunk port.
804 *
805 * @param connectPoint connect point
806 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
807 */
Pier Luigi96fe0772018-02-28 12:10:50 +0100808 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700809 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
810 VlanId nativeVlanId = getNativeVlanId(connectPoint);
811 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
812 }
813
814 /**
Charles Chan65238242017-06-22 18:03:14 -0700815 * Returns optional pair device ID of given device.
816 *
817 * @param deviceId device ID
818 * @return optional pair device ID. Might be empty if pair device is not configured
819 */
820 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
821 SegmentRoutingDeviceConfig deviceConfig =
822 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
823 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
824 }
825 /**
826 * Returns optional pair device local port of given device.
827 *
828 * @param deviceId device ID
829 * @return optional pair device ID. Might be empty if pair device is not configured
830 */
831 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
832 SegmentRoutingDeviceConfig deviceConfig =
833 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
834 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
835 }
836
837 /**
Charles Chan2fde6d42017-08-23 14:46:43 -0700838 * Determine if current instance is the master of given connect point.
839 *
840 * @param cp connect point
841 * @return true if current instance is the master of given connect point
842 */
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700843 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan2fde6d42017-08-23 14:46:43 -0700844 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
845 if (!isMaster) {
846 log.debug(NOT_MASTER, cp);
847 }
848 return isMaster;
849 }
850
851 /**
Charles Chan9640c812017-08-23 13:55:39 -0700852 * Returns locations of given resolved route.
853 *
854 * @param resolvedRoute resolved route
855 * @return locations of nexthop. Might be empty if next hop is not found
856 */
857 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
858 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
859 return Optional.ofNullable(hostService.getHost(hostId))
860 .map(Host::locations).orElse(Sets.newHashSet())
861 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
862 }
863
864 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800865 * Returns vlan port map of given device.
866 *
867 * @param deviceId device id
868 * @return vlan-port multimap
869 */
870 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
871 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
872
873 interfaceService.getInterfaces().stream()
874 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
875 .forEach(intf -> {
876 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700877 intf.vlanTagged().forEach(vlanTagged ->
878 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
879 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800880 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
881 });
882 vlanPortMap.removeAll(VlanId.NONE);
883
884 return vlanPortMap;
885 }
886
887 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800888 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800889 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700890 *
891 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800892 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800893 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700894 */
Charles Chan65238242017-06-22 18:03:14 -0700895 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700896 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800897 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
898 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700899 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800900 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800901 + "device {} not found", deviceId);
902 return -1;
903 }
904 }
905
906 /**
907 * Returns the next objective ID for the given portNumber, given the treatment.
908 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700909 * would result in different objectives. If the next object does not exist,
910 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800911 *
912 * @param deviceId Device ID
913 * @param portNum port number on device for which NextObjective is queried
914 * @param treatment the actions to apply on the packets (should include outport)
915 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700916 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700917 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800918 */
919 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
920 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700921 TrafficSelector meta,
922 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800923 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
924 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700925 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800926 } else {
Charles Chane849c192016-01-11 18:28:54 -0800927 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
928 + " not found", deviceId);
929 return -1;
930 }
931 }
932
Saurav Dasc88d4662017-05-15 15:34:25 -0700933 /**
934 * Returns the group handler object for the specified device id.
935 *
936 * @param devId the device identifier
937 * @return the groupHandler object for the device id, or null if not found
938 */
Charles Chan65238242017-06-22 18:03:14 -0700939 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700940 return groupHandlerMap.get(devId);
941 }
942
943 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700944 * Returns the default routing handler object.
945 *
946 * @return the default routing handler object
947 */
948 public DefaultRoutingHandler getRoutingHandler() {
949 return defaultRoutingHandler;
950 }
951
sanghob35a6192015-04-01 13:05:26 -0700952 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700953 @Override
954 public void process(PacketContext context) {
955
956 if (context.isHandled()) {
957 return;
958 }
959
960 InboundPacket pkt = context.inPacket();
961 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -0800962
963 if (ethernet == null) {
964 return;
965 }
966
Saurav Das7bcbe702017-06-13 15:35:54 -0700967 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
968 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -0800969 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700970 log.warn("Received unexpected ARP packet on {}",
971 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -0700972 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -0800973 return;
sanghob35a6192015-04-01 13:05:26 -0700974 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -0800975 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
976 //ipHandler.addToPacketBuffer(ipv4Packet);
977 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
978 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700979 } else {
Charles Chan50035632017-01-13 17:20:44 -0800980 // NOTE: We don't support IP learning at this moment so this
981 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -0800982 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700983 }
Pier Ventre10bd8d12016-11-26 21:05:22 -0800984 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
985 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -0800986 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -0800987 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -0800988 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
989 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
990 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
991 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
992 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
993 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -0700994 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -0700995 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -0800996 }
997 } else {
998 // NOTE: We don't support IP learning at this moment so this
999 // is not necessary. Also it causes duplication of DHCPv6 packets.
1000 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1001 }
sanghob35a6192015-04-01 13:05:26 -07001002 }
1003 }
1004 }
1005
sanghob35a6192015-04-01 13:05:26 -07001006 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001007 private Event event;
1008
1009 InternalEventHandler(Event event) {
1010 this.event = event;
1011 }
1012
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001013 @Override
sanghob35a6192015-04-01 13:05:26 -07001014 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001015 try {
1016 // TODO We should also change SR routing and PW to listen to TopologyEvents
1017 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1018 event.type() == LinkEvent.Type.LINK_UPDATED) {
1019 linkHandler.processLinkAdded((Link) event.subject());
1020 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1021 linkHandler.processLinkRemoved((Link) event.subject());
1022 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1023 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1024 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1025 DeviceId deviceId = ((Device) event.subject()).id();
1026 if (deviceService.isAvailable(deviceId)) {
1027 log.info("** DEVICE UP Processing device event {} "
1028 + "for available device {}",
1029 event.type(), ((Device) event.subject()).id());
1030 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001031 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001032 log.info(" ** DEVICE DOWN Processing device event {}"
1033 + " for unavailable device {}",
1034 event.type(), ((Device) event.subject()).id());
1035 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001036 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001037 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1038 // typically these calls come when device is added first time
1039 // so port filtering rules are handled at the device_added event.
1040 // port added calls represent all ports on the device,
1041 // enabled or not.
1042 log.trace("** PORT ADDED {}/{} -> {}",
1043 ((DeviceEvent) event).subject().id(),
1044 ((DeviceEvent) event).port().number(),
1045 event.type());
1046 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1047 // these calls happen for every subsequent event
1048 // ports enabled, disabled, switch goes away, comes back
1049 log.info("** PORT UPDATED {}/{} -> {}",
1050 event.subject(),
1051 ((DeviceEvent) event).port(),
1052 event.type());
1053 processPortUpdated(((Device) event.subject()),
1054 ((DeviceEvent) event).port());
1055 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1056 // Process topology event, needed for all modules relying on
1057 // topology service for path computation
1058 TopologyEvent topologyEvent = (TopologyEvent) event;
1059 log.info("Processing topology event {}, topology age {}, reasons {}",
1060 event.type(), topologyEvent.subject().time(),
1061 topologyEvent.reasons().size());
1062 topologyHandler.processTopologyChange(topologyEvent.reasons());
1063 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1064 hostHandler.processHostAddedEvent((HostEvent) event);
1065 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1066 hostHandler.processHostMovedEvent((HostEvent) event);
1067 routeHandler.processHostMovedEvent((HostEvent) event);
1068 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1069 hostHandler.processHostRemovedEvent((HostEvent) event);
1070 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1071 hostHandler.processHostUpdatedEvent((HostEvent) event);
1072 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1073 routeHandler.processRouteAdded((RouteEvent) event);
1074 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1075 routeHandler.processRouteUpdated((RouteEvent) event);
1076 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1077 routeHandler.processRouteRemoved((RouteEvent) event);
1078 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1079 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1080 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1081 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1082 event.type() == McastEvent.Type.SINKS_ADDED ||
1083 event.type() == McastEvent.Type.SINKS_REMOVED ||
1084 event.type() == McastEvent.Type.ROUTE_ADDED ||
1085 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1086 mcastHandler.processMcastEvent((McastEvent) event);
1087 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1088 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1089 Class configClass = netcfgEvent.configClass();
1090 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1091 appCfgHandler.processAppConfigAdded(netcfgEvent);
1092 log.info("App config event .. configuring network");
1093 cfgListener.configureNetwork();
1094 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1095 log.info("Segment Routing Device Config added for {}", event.subject());
1096 cfgListener.configureNetwork();
1097 } else if (configClass.equals(XConnectConfig.class)) {
1098 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1099 } else if (configClass.equals(InterfaceConfig.class)) {
1100 log.info("Interface Config added for {}", event.subject());
1101 cfgListener.configureNetwork();
1102 } else {
1103 log.error("Unhandled config class: {}", configClass);
1104 }
1105 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1106 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1107 Class configClass = netcfgEvent.configClass();
1108 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1109 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1110 log.info("App config event .. configuring network");
1111 cfgListener.configureNetwork();
1112 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1113 log.info("Segment Routing Device Config updated for {}", event.subject());
1114 createOrUpdateDeviceConfiguration();
1115 } else if (configClass.equals(XConnectConfig.class)) {
1116 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1117 } else if (configClass.equals(InterfaceConfig.class)) {
1118 log.info("Interface Config updated for {}", event.subject());
1119 createOrUpdateDeviceConfiguration();
1120 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1121 (InterfaceConfig) netcfgEvent.prevConfig().get());
1122 } else {
1123 log.error("Unhandled config class: {}", configClass);
1124 }
1125 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1126 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1127 Class configClass = netcfgEvent.configClass();
1128 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1129 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1130 log.info("App config event .. configuring network");
1131 cfgListener.configureNetwork();
1132 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1133 // TODO Handle sr device config removal
1134 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1135 } else if (configClass.equals(XConnectConfig.class)) {
1136 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1137 } else if (configClass.equals(InterfaceConfig.class)) {
1138 // TODO Handle interface removal
1139 log.info("InterfaceConfig removal is not handled in current implementation");
1140 } else {
1141 log.error("Unhandled config class: {}", configClass);
1142 }
1143 } else {
1144 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001145 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001146 } catch (Exception e) {
1147 log.error("SegmentRouting event handler thread thrown an exception: {}",
1148 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001149 }
sanghob35a6192015-04-01 13:05:26 -07001150 }
1151 }
1152
Saurav Das45f48152018-01-18 12:07:33 -08001153 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001154 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001155
1156 // NOTE: Punt ARP/NDP even when the device is not configured.
1157 // Host learning without network config is required for CORD config generator.
1158 routingRulePopulator.populateIpPunts(device.id());
1159 routingRulePopulator.populateArpNdpPunts(device.id());
1160
Charles Chan0b4e6182015-11-03 10:42:14 -08001161 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001162 log.warn("Device configuration unavailable. Device {} will be "
1163 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001164 return;
1165 }
Charles Chan2199c302016-04-23 17:36:10 -07001166 processDeviceAddedInternal(device.id());
1167 }
1168
1169 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001170 // Irrespective of whether the local is a MASTER or not for this device,
1171 // we need to create a SR-group-handler instance. This is because in a
1172 // multi-instance setup, any instance can initiate forwarding/next-objectives
1173 // for any switch (even if this instance is a SLAVE or not even connected
1174 // to the switch). To handle this, a default-group-handler instance is necessary
1175 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001176 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1177 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001178 DefaultGroupHandler groupHandler;
1179 try {
1180 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001181 createGroupHandler(deviceId,
1182 appId,
1183 deviceConfiguration,
1184 linkService,
1185 flowObjectiveService,
1186 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001187 } catch (DeviceConfigNotFoundException e) {
1188 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1189 return;
1190 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001191 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001192 deviceId);
1193 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001194 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001195
Charles Chan2199c302016-04-23 17:36:10 -07001196 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001197 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001198 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001199 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001200 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001201 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001202 }
Charles Chan5270ed02016-01-30 23:22:37 -08001203
Charles Chan03a73e02016-10-24 14:52:01 -07001204 appCfgHandler.init(deviceId);
Charles Chan2ff1bac2018-03-29 16:03:41 -07001205 hostHandler.init(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001206 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001207 }
1208
Saurav Das80980c72016-03-23 11:22:49 -07001209 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001210 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001211 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001212 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001213 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001214 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001215 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001216 portNextObjStore.entrySet().stream()
1217 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001218 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001219 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001220
Saurav Dasceccf242017-08-03 18:30:35 -07001221 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1222 if (gh != null) {
1223 gh.shutdown();
1224 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001225 // Note that a switch going down is associated with all of its links
1226 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001227 // while the link-downs are ignored. We cannot rely on the ordering of
1228 // events - i.e we cannot expect all link-downs to come before the
1229 // switch down - so we purge all seen-links for the switch before
1230 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001231 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001232 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001233 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001234 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001235
1236 // Cleanup all internal groupHandler stores for this device. Should be
1237 // done after all rerouting or rehashing has been completed
1238 groupHandlerMap.entrySet()
1239 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001240 }
1241
Saurav Das1a129a02016-11-18 15:21:57 -08001242 private void processPortUpdated(Device device, Port port) {
1243 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1244 log.warn("Device configuration uploading. Not handling port event for"
1245 + "dev: {} port: {}", device.id(), port.number());
1246 return;
1247 }
Saurav Das018605f2017-02-18 14:05:44 -08001248
1249 if (!mastershipService.isLocalMaster(device.id())) {
1250 log.debug("Not master for dev:{} .. not handling port updated event"
1251 + "for port {}", device.id(), port.number());
1252 return;
1253 }
1254
1255 // first we handle filtering rules associated with the port
1256 if (port.isEnabled()) {
1257 log.info("Switchport {}/{} enabled..programming filters",
1258 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001259 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001260 } else {
1261 log.info("Switchport {}/{} disabled..removing filters",
1262 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001263 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001264 }
Saurav Das1a129a02016-11-18 15:21:57 -08001265
1266 // portUpdated calls are for ports that have gone down or up. For switch
1267 // to switch ports, link-events should take care of any re-routing or
1268 // group editing necessary for port up/down. Here we only process edge ports
1269 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001270 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1271 VlanId untaggedVlan = getUntaggedVlanId(cp);
1272 VlanId nativeVlan = getNativeVlanId(cp);
1273 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001274
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001275 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001276 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001277 + "dev/port: {}/{}", device.id(), port.number());
1278 return;
1279 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001280 if (untaggedVlan != null) {
1281 processEdgePort(device, port, untaggedVlan, true);
1282 }
1283 if (nativeVlan != null) {
1284 processEdgePort(device, port, nativeVlan, true);
1285 }
1286 if (!taggedVlans.isEmpty()) {
1287 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1288 }
Saurav Das1a129a02016-11-18 15:21:57 -08001289 }
1290
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001291 private void processEdgePort(Device device, Port port, VlanId vlanId,
1292 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001293 boolean portUp = port.isEnabled();
1294 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001295 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001296 port.number(), vlanId);
Charles Chan47933752017-11-30 15:37:50 -08001297 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001298 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001299 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001300 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001301 }
1302
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001303 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001304 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001305 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001306 } else {
1307 log.warn("Group handler not found for dev:{}. Not handling edge port"
1308 + " {} event for port:{}", device.id(),
1309 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001310 }
1311 }
sangho1e575652015-05-14 00:39:53 -07001312
Charles Chan27fe1a52017-10-20 16:06:55 -07001313 private void createOrUpdateDeviceConfiguration() {
1314 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001315 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001316 deviceConfiguration = new DeviceConfiguration(this);
1317 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001318 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001319 deviceConfiguration.updateConfig();
1320 }
1321 }
1322
Pier Ventre10bd8d12016-11-26 21:05:22 -08001323 /**
1324 * Registers the given connect point with the NRS, this is necessary
1325 * to receive the NDP and ARP packets from the NRS.
1326 *
1327 * @param portToRegister connect point to register
1328 */
1329 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001330 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001331 portToRegister,
1332 neighbourHandler,
1333 appId
1334 );
1335 }
1336
Charles Chand6832882015-10-05 17:50:33 -07001337 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001338 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001339 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001340
Charles Chane849c192016-01-11 18:28:54 -08001341 /**
1342 * Constructs the internal network config listener.
1343 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001344 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001345 */
Charles Chan65238242017-06-22 18:03:14 -07001346 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001347 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001348 }
1349
Charles Chane849c192016-01-11 18:28:54 -08001350 /**
1351 * Reads network config and initializes related data structure accordingly.
1352 */
Charles Chan47933752017-11-30 15:37:50 -08001353 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001354 log.info("Configuring network ...");
Charles Chan27fe1a52017-10-20 16:06:55 -07001355 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001356
Charles Chan2c15aca2016-11-09 20:51:44 -08001357 arpHandler = new ArpHandler(srManager);
1358 icmpHandler = new IcmpHandler(srManager);
1359 ipHandler = new IpHandler(srManager);
1360 routingRulePopulator = new RoutingRulePopulator(srManager);
1361 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001362
1363 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1364 groupHandlerMap, tunnelStore);
1365 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1366 flowObjectiveService,
1367 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001368 // add a small delay to absorb multiple network config added notifications
1369 if (!programmingScheduled.get()) {
Saurav Dase7f51012018-02-09 17:26:45 -08001370 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das7bcbe702017-06-13 15:35:54 -07001371 programmingScheduled.set(true);
Charles Chan9b7217c2018-04-05 16:31:15 -07001372 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001373 }
Charles Chan2199c302016-04-23 17:36:10 -07001374 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001375 }
1376
Charles Chand6832882015-10-05 17:50:33 -07001377 @Override
1378 public void event(NetworkConfigEvent event) {
Charles Chan7a888e82018-03-21 16:57:47 -07001379 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1380 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1381 switch (event.type()) {
1382 case CONFIG_ADDED:
1383 case CONFIG_UPDATED:
1384 case CONFIG_REMOVED:
1385 log.trace("Schedule Network Config event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001386 mainEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan7a888e82018-03-21 16:57:47 -07001387 break;
1388 default:
1389 break;
Charles Chand6832882015-10-05 17:50:33 -07001390 }
1391 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001392
Charles Chan50443e82018-01-03 16:26:32 -08001393 @Override
1394 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001395 if (event.type() == CONFIG_REGISTERED ||
1396 event.type() == CONFIG_UNREGISTERED) {
1397 log.debug("Ignore event {} due to type mismatch", event);
1398 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001399 }
Saurav Dase7f51012018-02-09 17:26:45 -08001400
1401 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1402 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1403 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001404 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001405 log.debug("Ignore event {} due to class mismatch", event);
1406 return false;
1407 }
1408
1409 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001410 }
1411
Saurav Das7bcbe702017-06-13 15:35:54 -07001412 private final class ConfigChange implements Runnable {
1413 @Override
1414 public void run() {
1415 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001416 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001417 for (Device device : deviceService.getDevices()) {
1418 processDeviceAdded(device);
1419 }
1420 defaultRoutingHandler.startPopulationProcess();
1421 }
1422 }
Charles Chand6832882015-10-05 17:50:33 -07001423 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001424
Charles Chan7a888e82018-03-21 16:57:47 -07001425 private class InternalLinkListener implements LinkListener {
1426 @Override
1427 public void event(LinkEvent event) {
1428 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1429 event.type() == LinkEvent.Type.LINK_UPDATED ||
1430 event.type() == LinkEvent.Type.LINK_REMOVED) {
1431 log.trace("Schedule Link event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001432 mainEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan7a888e82018-03-21 16:57:47 -07001433 }
1434 }
1435 }
1436
1437 private class InternalDeviceListener implements DeviceListener {
1438 @Override
1439 public void event(DeviceEvent event) {
1440 switch (event.type()) {
1441 case DEVICE_ADDED:
1442 case PORT_UPDATED:
1443 case PORT_ADDED:
1444 case DEVICE_UPDATED:
1445 case DEVICE_AVAILABILITY_CHANGED:
1446 log.trace("Schedule Device event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001447 mainEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan7a888e82018-03-21 16:57:47 -07001448 break;
1449 default:
1450 }
1451 }
1452 }
1453
1454 private class InternalTopologyListener implements TopologyListener {
1455 @Override
1456 public void event(TopologyEvent event) {
1457 switch (event.type()) {
1458 case TOPOLOGY_CHANGED:
1459 log.trace("Schedule Topology event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001460 mainEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan7a888e82018-03-21 16:57:47 -07001461 break;
1462 default:
1463 }
1464 }
1465 }
1466
Charles Chan68aa62d2015-11-09 16:37:23 -08001467 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001468 @Override
1469 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001470 switch (event.type()) {
1471 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001472 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001473 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001474 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001475 log.trace("Schedule Host event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001476 hostEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan68aa62d2015-11-09 16:37:23 -08001477 break;
1478 default:
1479 log.warn("Unsupported host event type: {}", event.type());
1480 break;
1481 }
1482 }
1483 }
1484
Charles Chand55e84d2016-03-30 17:54:24 -07001485 private class InternalMcastListener implements McastListener {
1486 @Override
1487 public void event(McastEvent event) {
1488 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001489 case SOURCES_ADDED:
1490 case SOURCES_REMOVED:
1491 case SINKS_ADDED:
1492 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001493 case ROUTE_REMOVED:
Charles Chan7a888e82018-03-21 16:57:47 -07001494 log.trace("Schedule Mcast event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001495 mcastEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Pier Luigi9930da52018-02-02 16:19:11 +01001496 break;
1497 case ROUTE_ADDED:
Charles Chand55e84d2016-03-30 17:54:24 -07001498 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001499 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001500 break;
1501 }
1502 }
1503 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001504
Charles Chan03a73e02016-10-24 14:52:01 -07001505 private class InternalRouteEventListener implements RouteListener {
1506 @Override
1507 public void event(RouteEvent event) {
1508 switch (event.type()) {
1509 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001510 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001511 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001512 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001513 log.trace("Schedule Route event {}", event);
Charles Chan9b7217c2018-04-05 16:31:15 -07001514 routeEventExecutor.schedule(new InternalEventHandler(event), 100, TimeUnit.MILLISECONDS);
Charles Chan2fde6d42017-08-23 14:46:43 -07001515 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001516 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001517 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001518 break;
1519 }
1520 }
1521 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001522
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001523 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1524 try {
1525 Set<Interface> intfs = conf.getInterfaces();
1526 Set<Interface> prevIntfs = prevConf.getInterfaces();
1527
1528 // Now we only handle one interface config at each port.
1529 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1530 log.warn("Interface update aborted - one at a time is allowed, " +
1531 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1532 return;
1533 }
1534
1535 Interface intf = intfs.stream().findFirst().get();
1536 Interface prevIntf = prevIntfs.stream().findFirst().get();
1537
1538 DeviceId deviceId = intf.connectPoint().deviceId();
1539 PortNumber portNum = intf.connectPoint().port();
1540
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001541 removeSubnetConfig(prevIntf.connectPoint(),
1542 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1543 new HashSet<>(intf.ipAddressesList())));
1544
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001545 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1546 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1547 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1548 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1549 // Update filtering objective and L2IG group bucket
1550 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1551 } else {
1552 // RemoveVlanNative
1553 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1554 }
1555 }
1556
1557 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1558 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1559 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1560 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1561 // Update filtering objective and L2IG group bucket
1562 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1563 } else {
1564 // RemoveVlanUntagged
1565 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1566 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001567 }
1568
1569 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1570 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001571 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1572 .filter(i -> !intf.vlanUntagged().equals(i))
1573 .filter(i -> !intf.vlanNative().equals(i))
1574 .forEach(vlanId -> updateVlanConfigInternal(
1575 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001576 }
1577
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001578 if (!intf.vlanNative().equals(VlanId.NONE)
1579 && !prevIntf.vlanNative().equals(intf.vlanNative())
1580 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1581 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1582 // Update filtering objective and L2IG group bucket
1583 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1584 } else {
1585 // AddVlanNative
1586 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1587 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001588 }
1589
1590 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1591 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001592 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1593 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1594 .filter(i -> !prevIntf.vlanNative().equals(i))
1595 .forEach(vlanId -> updateVlanConfigInternal(
1596 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001597 );
1598 }
1599
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001600 if (!intf.vlanUntagged().equals(VlanId.NONE)
1601 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1602 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1603 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1604 // Update filtering objective and L2IG group bucket
1605 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1606 } else {
1607 // AddVlanUntagged
1608 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1609 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001610 }
1611 addSubnetConfig(prevIntf.connectPoint(),
1612 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1613 new HashSet<>(prevIntf.ipAddressesList())));
1614 } catch (ConfigException e) {
1615 log.error("Error in configuration");
1616 }
1617 }
1618
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001619 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1620 VlanId vlanId, boolean pushVlan) {
1621 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1622 if (grpHandler == null) {
1623 log.warn("Failed to retrieve group handler for device {}", deviceId);
1624 return;
1625 }
1626
1627 // Update filtering objective for a single port
1628 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1629 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1630
1631 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1632 // Update L2IG bucket of the port
1633 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1634 } else {
1635 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1636 }
1637 }
1638
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001639 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1640 VlanId vlanId, boolean pushVlan, boolean install) {
1641 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1642 if (grpHandler == null) {
1643 log.warn("Failed to retrieve group handler for device {}", deviceId);
1644 return;
1645 }
1646
1647 // Update filtering objective for a single port
1648 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1649
1650 // Update filtering objective for multicast ingress port
1651 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1652
1653 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1654
1655 if (nextId != -1 && !install) {
1656 // Update next objective for a single port as an output port
1657 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001658 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001659 // Remove L2 Bridging rule and L3 Unicast rule to the host
1660 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1661 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1662 // only if there is no port configured on that VLAN ID
1663 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1664 // Remove broadcast forwarding rule for the VLAN
1665 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1666 // Remove L2FG for VLAN
1667 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1668 } else {
1669 // Remove L2IG of the port
1670 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1671 }
1672 } else if (install) {
1673 if (nextId != -1) {
1674 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001675 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001676 } else {
1677 // Create L2FG for VLAN
1678 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1679 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1680 }
1681 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1682 } else {
1683 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1684 }
1685 }
1686
1687 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1688 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1689 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1690
1691 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1692 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1693 .filter(intf -> !intf.connectPoint().equals(cp))
1694 .flatMap(intf -> intf.ipAddressesList().stream())
1695 .collect(Collectors.toSet());
1696 // 1. Partial subnet population
1697 // Remove routing rules for removed subnet from previous configuration,
1698 // which does not also exist in other interfaces in the same device
1699 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1700 .map(InterfaceIpAddress::subnetAddress)
1701 .collect(Collectors.toSet());
1702
1703 defaultRoutingHandler.revokeSubnet(
1704 ipPrefixSet.stream()
1705 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1706 .collect(Collectors.toSet()));
1707
1708 // 2. Interface IP punts
1709 // Remove IP punts for old Intf address
1710 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1711 .map(InterfaceIpAddress::ipAddress)
1712 .collect(Collectors.toSet());
1713 ipAddressSet.stream()
1714 .map(InterfaceIpAddress::ipAddress)
1715 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1716 .forEach(interfaceIpAddress ->
1717 routingRulePopulator.revokeSingleIpPunts(
1718 cp.deviceId(), interfaceIpAddress));
1719
1720 // 3. Host unicast routing rule
1721 // Remove unicast routing rule
1722 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1723 }
1724
1725 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1726 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1727 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1728
1729 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1730 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1731 .filter(intf -> !intf.connectPoint().equals(cp))
1732 .flatMap(intf -> intf.ipAddressesList().stream())
1733 .collect(Collectors.toSet());
1734 // 1. Partial subnet population
1735 // Add routing rules for newly added subnet, which does not also exist in
1736 // other interfaces in the same device
1737 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1738 .map(InterfaceIpAddress::subnetAddress)
1739 .collect(Collectors.toSet());
1740
1741 defaultRoutingHandler.populateSubnet(
1742 Collections.singleton(cp),
1743 ipPrefixSet.stream()
1744 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1745 .collect(Collectors.toSet()));
1746
1747 // 2. Interface IP punts
1748 // Add IP punts for new Intf address
1749 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1750 .map(InterfaceIpAddress::ipAddress)
1751 .collect(Collectors.toSet());
1752 ipAddressSet.stream()
1753 .map(InterfaceIpAddress::ipAddress)
1754 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1755 .forEach(interfaceIpAddress ->
1756 routingRulePopulator.populateSingleIpPunts(
1757 cp.deviceId(), interfaceIpAddress));
1758
1759 // 3. Host unicast routing rule
1760 // Add unicast routing rule
1761 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1762 }
sanghob35a6192015-04-01 13:05:26 -07001763}