blob: c200d74899550ed66e896f678ce1482a2591af68 [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;
Pier96f63cb2018-04-17 16:29:56 +020042import org.onosproject.cluster.NodeId;
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;
Pier96f63cb2018-04-17 16:29:56 +020078import org.onosproject.net.intent.WorkPartitionService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070079import org.onosproject.net.intf.Interface;
80import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080081import org.onosproject.net.link.LinkEvent;
82import org.onosproject.net.link.LinkListener;
83import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070084import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080085import org.onosproject.net.packet.InboundPacket;
86import org.onosproject.net.packet.PacketContext;
87import org.onosproject.net.packet.PacketProcessor;
88import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010089import org.onosproject.net.topology.TopologyEvent;
90import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070091import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070092import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070093import org.onosproject.routeservice.RouteEvent;
94import org.onosproject.routeservice.RouteListener;
95import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -070096import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
97import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -080098import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070099import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700100import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700101import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700102import org.onosproject.segmentrouting.grouphandler.DestinationSet;
103import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100104import org.onosproject.segmentrouting.mcast.McastHandler;
105import org.onosproject.segmentrouting.mcast.McastRole;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700106import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700109import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800110
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800111import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700112import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800114import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
115
Saurav Das7bcbe702017-06-13 15:35:54 -0700116import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigib29144d2018-01-15 18:06:43 +0100117import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700118import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800119import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700120import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700121import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700122import org.onosproject.store.service.EventuallyConsistentMap;
123import org.onosproject.store.service.EventuallyConsistentMapBuilder;
124import org.onosproject.store.service.StorageService;
125import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800126import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700127import org.slf4j.Logger;
128import org.slf4j.LoggerFactory;
129
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700130import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800131import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800132import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800133import java.util.HashSet;
134import java.util.List;
135import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800136import java.util.Optional;
137import java.util.Set;
138import java.util.concurrent.ConcurrentHashMap;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800139import java.util.concurrent.Executors;
140import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800141import java.util.concurrent.TimeUnit;
142import java.util.concurrent.atomic.AtomicBoolean;
143import java.util.stream.Collectors;
sanghob35a6192015-04-01 13:05:26 -0700144
Charles Chan3e783d02016-02-26 22:19:52 -0800145import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800146import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700147import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800148import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
149import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800150
Charles Chane849c192016-01-11 18:28:54 -0800151/**
152 * Segment routing manager.
153 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700154@Service
155@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700156public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700157
Charles Chan2c15aca2016-11-09 20:51:44 -0800158 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700159 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700162 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800165 private NeighbourResolutionService neighbourResolutionService;
166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100168 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700169
170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700171 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700174 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan47933752017-11-30 15:37:50 -0800177 HostLocationProbingService probingService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100180 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800183 DeviceAdminService deviceAdminService;
184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800186 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700187
188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100189 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700190
Charles Chan5270ed02016-01-30 23:22:37 -0800191 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800192 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700193
194 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800195 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700196
197 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100198 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700199
200 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800201 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700202
203 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700204 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800205
206 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800207 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800208
Saurav Das80980c72016-03-23 11:22:49 -0700209 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800210 public InterfaceService interfaceService;
211
Pier Luigieba73a02018-01-16 10:47:50 +0100212 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
213 public ClusterService clusterService;
214
215 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier96f63cb2018-04-17 16:29:56 +0200216 public WorkPartitionService workPartitionService;
Pier Luigieba73a02018-01-16 10:47:50 +0100217
Charles Chan47933752017-11-30 15:37:50 -0800218 @Property(name = "activeProbing", boolValue = true,
219 label = "Enable active probing to discover dual-homed hosts.")
220 boolean activeProbing = true;
221
Charles Chan03a73e02016-10-24 14:52:01 -0700222 ArpHandler arpHandler = null;
223 IcmpHandler icmpHandler = null;
224 IpHandler ipHandler = null;
225 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700226 ApplicationId appId;
227 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700228
Charles Chan03a73e02016-10-24 14:52:01 -0700229 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700230 private TunnelHandler tunnelHandler = null;
231 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700232 private InternalPacketProcessor processor = null;
233 private InternalLinkListener linkListener = null;
234 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700235 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100236 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800237 McastHandler mcastHandler = null;
238 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800239 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800240 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800241 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800242 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100243 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800244 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700245 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
246 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700247 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100248 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sanghob35a6192015-04-01 13:05:26 -0700249
Charles Chan9b7217c2018-04-05 16:31:15 -0700250 // Handles device, link, topology and network config events
251 private ScheduledExecutorService mainEventExecutor = Executors
252 .newScheduledThreadPool(1, groupedThreads("sr-event-main", "%d", log));
sanghob35a6192015-04-01 13:05:26 -0700253
Charles Chan9b7217c2018-04-05 16:31:15 -0700254 // Handles host, route, mcast events
255 private ScheduledExecutorService hostEventExecutor = Executors
256 .newScheduledThreadPool(1, groupedThreads("sr-event-host", "%d", log));
257 private ScheduledExecutorService routeEventExecutor = Executors
258 .newScheduledThreadPool(1, groupedThreads("sr-event-route", "%d", log));
259 private ScheduledExecutorService mcastEventExecutor = Executors
260 .newScheduledThreadPool(1, groupedThreads("sr-event-mcast", "%d", log));
261
262
263 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800264 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700265 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700266 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800267 */
Charles Chan47933752017-11-30 15:37:50 -0800268 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700269 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800270 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700271 * Per device next objective ID store with (device id + vlanid) as key.
272 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800273 */
Charles Chan47933752017-11-30 15:37:50 -0800274 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800275 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800276 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700277 * Per device next objective ID store with (device id + port + treatment + meta) as key.
278 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800279 */
Charles Chan47933752017-11-30 15:37:50 -0800280 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800281 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800282
Saurav Das4ce45962015-11-24 23:21:05 -0800283 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
284 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700285
Saurav Das7bcbe702017-06-13 15:35:54 -0700286 private AtomicBoolean programmingScheduled = new AtomicBoolean();
287
Charles Chand55e84d2016-03-30 17:54:24 -0700288 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700289 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
290 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700291 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700292 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800293 public SegmentRoutingDeviceConfig createConfig() {
294 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700295 }
296 };
Pier Ventref34966c2016-11-07 16:21:04 -0800297
Charles Chand55e84d2016-03-30 17:54:24 -0700298 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700299 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
300 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700301 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800302 @Override
303 public SegmentRoutingAppConfig createConfig() {
304 return new SegmentRoutingAppConfig();
305 }
306 };
Pier Ventref34966c2016-11-07 16:21:04 -0800307
Charles Chanfc5c7802016-05-17 13:13:55 -0700308 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
309 new ConfigFactory<ApplicationId, XConnectConfig>(
310 SubjectFactories.APP_SUBJECT_FACTORY,
311 XConnectConfig.class, "xconnect") {
312 @Override
313 public XConnectConfig createConfig() {
314 return new XConnectConfig();
315 }
316 };
Pier Ventref34966c2016-11-07 16:21:04 -0800317
Charles Chand55e84d2016-03-30 17:54:24 -0700318 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700319 new ConfigFactory<ApplicationId, McastConfig>(
320 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700321 McastConfig.class, "multicast") {
322 @Override
323 public McastConfig createConfig() {
324 return new McastConfig();
325 }
326 };
327
Charles Chan65238242017-06-22 18:03:14 -0700328 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700329 private static int numOfEventsQueued = 0;
330 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700331 private static int numOfHandlerExecution = 0;
332 private static int numOfHandlerScheduled = 0;
333
Charles Chan116188d2016-02-18 14:22:42 -0800334 /**
335 * Segment Routing App ID.
336 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800337 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800338
Charles Chane849c192016-01-11 18:28:54 -0800339 /**
340 * The default VLAN ID assigned to the interfaces without subnet config.
341 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800342 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700343
sanghob35a6192015-04-01 13:05:26 -0700344 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800345 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800346 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700347
348 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700349 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700350 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700351 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700352 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700353 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700354 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700355 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700356 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700357
Charles Chan59cc16d2017-02-02 16:20:42 -0800358 log.debug("Creating EC map vlannextobjectivestore");
359 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
360 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
361 vlanNextObjStore = vlanNextObjMapBuilder
362 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700363 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700364 .withTimestampProvider((k, v) -> new WallClockTimestamp())
365 .build();
366
Saurav Das4ce45962015-11-24 23:21:05 -0800367 log.debug("Creating EC map subnetnextobjectivestore");
368 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
369 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
370 portNextObjStore = portNextObjMapBuilder
371 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700372 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800373 .withTimestampProvider((k, v) -> new WallClockTimestamp())
374 .build();
375
sangho0b2b6d12015-05-20 22:16:38 -0700376 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
377 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700378 tunnelStore = tunnelMapBuilder
379 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700380 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700381 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700382 .build();
383
384 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
385 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700386 policyStore = policyMapBuilder
387 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700388 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700389 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700390 .build();
391
Saurav Das80980c72016-03-23 11:22:49 -0700392 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800393 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700394 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800395 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800396 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
397 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700398 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800399 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700400 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800401 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800402 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
403 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800404 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
405 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700406 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700407 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700408 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
409 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800410 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
411 "staleLinkAge", "15000");
412 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
413 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800414 compCfgService.registerProperties(getClass());
415 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700416
Charles Chanb8e10c82015-10-14 11:24:40 -0700417 processor = new InternalPacketProcessor();
418 linkListener = new InternalLinkListener();
419 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700420 appCfgHandler = new AppConfigHandler(this);
421 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700422 mcastHandler = new McastHandler(this);
423 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800424 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700425 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800426 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800427 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100428 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700429
Charles Chan3e783d02016-02-26 22:19:52 -0800430 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700431 cfgService.registerConfigFactory(deviceConfigFactory);
432 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700433 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700434 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800435 log.info("Configuring network before adding listeners");
Charles Chan132393a2018-01-04 14:26:07 -0800436 cfgListener.configureNetwork();
437
Charles Chan5270ed02016-01-30 23:22:37 -0800438 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700439 packetService.addProcessor(processor, PacketProcessor.director(2));
440 linkService.addListener(linkListener);
441 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700442 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700443 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100444 topologyService.addListener(topologyListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700445
Charles Chanb39777c2018-03-09 15:53:44 -0800446 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800447 l2TunnelHandler.init();
448
sanghob35a6192015-04-01 13:05:26 -0700449 log.info("Started");
450 }
451
Saurav Das45f48152018-01-18 12:07:33 -0800452 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700453 return new KryoNamespace.Builder()
454 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700455 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800456 VlanNextObjectiveStoreKey.class,
457 DestinationSet.class,
458 NextNeighbors.class,
459 Tunnel.class,
460 DefaultTunnel.class,
461 Policy.class,
462 TunnelPolicy.class,
463 Policy.Type.class,
464 PortNextObjectiveStoreKey.class,
465 XConnectStoreKey.class,
466 L2Tunnel.class,
467 L2TunnelPolicy.class,
468 DefaultL2Tunnel.class,
469 DefaultL2TunnelPolicy.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700470 );
471 }
472
sanghob35a6192015-04-01 13:05:26 -0700473 @Deactivate
474 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700475 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700476 cfgService.unregisterConfigFactory(deviceConfigFactory);
477 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700478 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700479 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800480 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700481
Charles Chanc7a8a682017-06-19 00:43:31 -0700482 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700483 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700484 linkService.removeListener(linkListener);
485 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700486 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700487 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100488 topologyService.removeListener(topologyListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700489
Charles Chan0aa674e2017-02-23 15:44:08 -0800490 neighbourResolutionService.unregisterNeighbourHandlers(appId);
491
sanghob35a6192015-04-01 13:05:26 -0700492 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700493 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700494 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700495 groupHandlerMap.clear();
496
Saurav Das7bcbe702017-06-13 15:35:54 -0700497 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800498 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700499 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700500 tunnelStore.destroy();
501 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100502
503 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700504 log.info("Stopped");
505 }
506
Charles Chan47933752017-11-30 15:37:50 -0800507 @Modified
508 private void modified(ComponentContext context) {
509 Dictionary<?, ?> properties = context.getProperties();
510 if (properties == null) {
511 return;
512 }
513
514 String strActiveProving = Tools.get(properties, "activeProbing");
515 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
516
517 if (expectActiveProbing != activeProbing) {
518 activeProbing = expectActiveProbing;
519 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
520 }
521 }
522
sangho1e575652015-05-14 00:39:53 -0700523 @Override
524 public List<Tunnel> getTunnels() {
525 return tunnelHandler.getTunnels();
526 }
527
528 @Override
sangho71abe1b2015-06-29 14:58:47 -0700529 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
530 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700531 }
532
533 @Override
sangho71abe1b2015-06-29 14:58:47 -0700534 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700535 for (Policy policy: policyHandler.getPolicies()) {
536 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
537 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
538 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
539 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700540 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700541 }
542 }
543 }
sangho71abe1b2015-06-29 14:58:47 -0700544 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700545 }
546
547 @Override
sangho71abe1b2015-06-29 14:58:47 -0700548 public PolicyHandler.Result removePolicy(Policy policy) {
549 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700550 }
551
552 @Override
sangho71abe1b2015-06-29 14:58:47 -0700553 public PolicyHandler.Result createPolicy(Policy policy) {
554 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700555 }
556
557 @Override
558 public List<Policy> getPolicies() {
559 return policyHandler.getPolicies();
560 }
561
Saurav Das59232cf2016-04-27 18:35:50 -0700562 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700563 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
564 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700565 }
566
567 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800568 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700569 return l2TunnelHandler.getL2Tunnels();
570 }
571
572 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800573 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700574 return l2TunnelHandler.getL2Policies();
575 }
576
Saurav Das5a356042018-04-06 20:16:01 -0700577 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700578 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700579 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
580
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700581 // get both added and pending pseudowires
582 List<L2TunnelDescription> pseudowires = new ArrayList<>();
583 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
584 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700585 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700586
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700587 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
588
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700589 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
590 L2TunnelHandler.Result res;
591 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
592 res = addPseudowire(pw);
593 if (res != L2TunnelHandler.Result.SUCCESS) {
594 log.error("Pseudowire with id {} can not be instantiated !", res);
595 retRes = res;
596 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700597 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700598
599 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700600 }
601
602 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800603 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700604 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700605 }
606
607 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800608 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700609 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700610 }
611
612 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700613 public void rerouteNetwork() {
614 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700615 }
616
Charles Chanc81c45b2016-10-20 17:02:44 -0700617 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800618 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
619 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800620 deviceConfiguration.getRouters().forEach(device ->
621 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700622 return deviceSubnetMap;
623 }
624
Saurav Dasc88d4662017-05-15 15:34:25 -0700625
626 @Override
627 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
628 if (defaultRoutingHandler != null) {
629 return defaultRoutingHandler.getCurrentEmcpSpgMap();
630 } else {
631 return null;
632 }
633 }
634
635 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700636 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
637 if (dsNextObjStore != null) {
638 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700639 } else {
640 return ImmutableMap.of();
641 }
642 }
643
Saurav Dasceccf242017-08-03 18:30:35 -0700644 @Override
645 public void verifyGroups(DeviceId id) {
646 DefaultGroupHandler gh = groupHandlerMap.get(id);
647 if (gh != null) {
648 gh.triggerBucketCorrector();
649 }
650 }
651
Saurav Dasc568c342018-01-25 09:49:01 -0800652 @Override
653 public ImmutableMap<Link, Boolean> getSeenLinks() {
654 return linkHandler.getSeenLinks();
655 }
656
657 @Override
658 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
659 return linkHandler.getDownedPorts();
660 }
661
Pier Luigib29144d2018-01-15 18:06:43 +0100662 @Override
663 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
664 return mcastHandler.getMcastNextIds(mcastIp);
665 }
666
667 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100668 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100669 return mcastHandler.getMcastRoles(mcastIp);
670 }
671
672 @Override
673 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
674 return mcastHandler.getMcastPaths(mcastIp);
675 }
676
Pier96f63cb2018-04-17 16:29:56 +0200677 @Override
Pierb1fe7382018-04-17 17:25:22 +0200678 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
679 ConnectPoint sourcecp) {
680 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
681 }
682
683 @Override
Pier96f63cb2018-04-17 16:29:56 +0200684 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
685 return mcastHandler.getMcastLeaders(mcastIp);
686 }
687
sanghof9d0bf12015-05-19 11:57:42 -0700688 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700689 * Extracts the application ID from the manager.
690 *
691 * @return application ID
692 */
693 public ApplicationId appId() {
694 return appId;
695 }
696
697 /**
698 * Returns the device configuration.
699 *
700 * @return device configuration
701 */
702 public DeviceConfiguration deviceConfiguration() {
703 return deviceConfiguration;
704 }
705
706 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700707 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700708 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700709 *
710 * @return next objective ID store
711 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700712 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
713 dsNextObjStore() {
714 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700715 }
716
717 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700718 * Per device next objective ID store with (device id + vlanid) as key.
719 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700720 *
721 * @return vlan next object store
722 */
723 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
724 return vlanNextObjStore;
725 }
726
727 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700728 * Per device next objective ID store with (device id + port + treatment + meta) as key.
729 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700730 *
731 * @return port next object store.
732 */
733 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
734 return portNextObjStore;
735 }
736
737 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700738 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
739 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700740 *
741 * @return MPLS-ECMP value
742 */
743 public boolean getMplsEcmp() {
744 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
745 .getConfig(this.appId, SegmentRoutingAppConfig.class);
746 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
747 }
748
749 /**
sanghof9d0bf12015-05-19 11:57:42 -0700750 * Returns the tunnel object with the tunnel ID.
751 *
752 * @param tunnelId Tunnel ID
753 * @return Tunnel reference
754 */
sangho1e575652015-05-14 00:39:53 -0700755 public Tunnel getTunnel(String tunnelId) {
756 return tunnelHandler.getTunnel(tunnelId);
757 }
758
Charles Chan7ffd81f2017-02-08 15:52:08 -0800759 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700760 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800761 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800762 * <p>
763 * Only returns the first match if there are multiple untagged VLAN configured
764 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700765 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800766 * @param connectPoint connect point
767 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700768 */
Charles Chan65238242017-06-22 18:03:14 -0700769 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800770 return interfaceService.getInterfacesByPort(connectPoint).stream()
771 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
772 .map(Interface::vlanUntagged)
773 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700774 }
775
sangho1e575652015-05-14 00:39:53 -0700776 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800777 * Returns tagged VLAN configured on given connect point.
778 * <p>
779 * Returns all matches if there are multiple tagged VLAN configured
780 * on the connect point.
781 *
782 * @param connectPoint connect point
783 * @return tagged VLAN or empty set if not configured
784 */
Charles Chan65238242017-06-22 18:03:14 -0700785 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800786 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
787 return interfaces.stream()
788 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700789 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800790 .collect(Collectors.toSet());
791 }
792
793 /**
794 * Returns native VLAN configured on given connect point.
795 * <p>
796 * Only returns the first match if there are multiple native VLAN configured
797 * on the connect point.
798 *
799 * @param connectPoint connect point
800 * @return native VLAN or null if not configured
801 */
Charles Chan65238242017-06-22 18:03:14 -0700802 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800803 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
804 return interfaces.stream()
805 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
806 .map(Interface::vlanNative)
807 .findFirst()
808 .orElse(null);
809 }
810
811 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700812 * Returns internal VLAN for untagged hosts on given connect point.
813 * <p>
814 * The internal VLAN is either vlan-untagged for an access port,
815 * or vlan-native for a trunk port.
816 *
817 * @param connectPoint connect point
818 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
819 */
Pier Luigi96fe0772018-02-28 12:10:50 +0100820 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700821 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
822 VlanId nativeVlanId = getNativeVlanId(connectPoint);
823 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
824 }
825
826 /**
Charles Chan65238242017-06-22 18:03:14 -0700827 * Returns optional pair device ID of given device.
828 *
829 * @param deviceId device ID
830 * @return optional pair device ID. Might be empty if pair device is not configured
831 */
832 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
833 SegmentRoutingDeviceConfig deviceConfig =
834 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
835 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
836 }
837 /**
838 * Returns optional pair device local port of given device.
839 *
840 * @param deviceId device ID
841 * @return optional pair device ID. Might be empty if pair device is not configured
842 */
843 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
844 SegmentRoutingDeviceConfig deviceConfig =
845 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
846 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
847 }
848
849 /**
Charles Chan2fde6d42017-08-23 14:46:43 -0700850 * Determine if current instance is the master of given connect point.
851 *
852 * @param cp connect point
853 * @return true if current instance is the master of given connect point
854 */
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700855 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan2fde6d42017-08-23 14:46:43 -0700856 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
857 if (!isMaster) {
858 log.debug(NOT_MASTER, cp);
859 }
860 return isMaster;
861 }
862
863 /**
Charles Chan9640c812017-08-23 13:55:39 -0700864 * Returns locations of given resolved route.
865 *
866 * @param resolvedRoute resolved route
867 * @return locations of nexthop. Might be empty if next hop is not found
868 */
869 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
870 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
871 return Optional.ofNullable(hostService.getHost(hostId))
872 .map(Host::locations).orElse(Sets.newHashSet())
873 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
874 }
875
876 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800877 * Returns vlan port map of given device.
878 *
879 * @param deviceId device id
880 * @return vlan-port multimap
881 */
882 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
883 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
884
885 interfaceService.getInterfaces().stream()
886 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
887 .forEach(intf -> {
888 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700889 intf.vlanTagged().forEach(vlanTagged ->
890 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
891 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800892 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
893 });
894 vlanPortMap.removeAll(VlanId.NONE);
895
896 return vlanPortMap;
897 }
898
899 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800900 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800901 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700902 *
903 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800904 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800905 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700906 */
Charles Chan65238242017-06-22 18:03:14 -0700907 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700908 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800909 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
910 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700911 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800912 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800913 + "device {} not found", deviceId);
914 return -1;
915 }
916 }
917
918 /**
919 * Returns the next objective ID for the given portNumber, given the treatment.
920 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700921 * would result in different objectives. If the next object does not exist,
922 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800923 *
924 * @param deviceId Device ID
925 * @param portNum port number on device for which NextObjective is queried
926 * @param treatment the actions to apply on the packets (should include outport)
927 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700928 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700929 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800930 */
931 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
932 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700933 TrafficSelector meta,
934 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800935 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
936 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700937 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800938 } else {
Charles Chane849c192016-01-11 18:28:54 -0800939 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
940 + " not found", deviceId);
941 return -1;
942 }
943 }
944
Saurav Dasc88d4662017-05-15 15:34:25 -0700945 /**
946 * Returns the group handler object for the specified device id.
947 *
948 * @param devId the device identifier
949 * @return the groupHandler object for the device id, or null if not found
950 */
Charles Chan65238242017-06-22 18:03:14 -0700951 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700952 return groupHandlerMap.get(devId);
953 }
954
955 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700956 * Returns the default routing handler object.
957 *
958 * @return the default routing handler object
959 */
960 public DefaultRoutingHandler getRoutingHandler() {
961 return defaultRoutingHandler;
962 }
963
sanghob35a6192015-04-01 13:05:26 -0700964 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700965 @Override
966 public void process(PacketContext context) {
967
968 if (context.isHandled()) {
969 return;
970 }
971
972 InboundPacket pkt = context.inPacket();
973 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -0800974
975 if (ethernet == null) {
976 return;
977 }
978
Saurav Das7bcbe702017-06-13 15:35:54 -0700979 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
980 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -0800981 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700982 log.warn("Received unexpected ARP packet on {}",
983 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -0700984 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -0800985 return;
sanghob35a6192015-04-01 13:05:26 -0700986 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -0800987 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
988 //ipHandler.addToPacketBuffer(ipv4Packet);
989 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
990 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700991 } else {
Charles Chan50035632017-01-13 17:20:44 -0800992 // NOTE: We don't support IP learning at this moment so this
993 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -0800994 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -0700995 }
Pier Ventre10bd8d12016-11-26 21:05:22 -0800996 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
997 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -0800998 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -0800999 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001000 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1001 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1002 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1003 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1004 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1005 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001006 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001007 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001008 }
1009 } else {
1010 // NOTE: We don't support IP learning at this moment so this
1011 // is not necessary. Also it causes duplication of DHCPv6 packets.
1012 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1013 }
sanghob35a6192015-04-01 13:05:26 -07001014 }
1015 }
1016 }
1017
sanghob35a6192015-04-01 13:05:26 -07001018 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001019 private Event event;
1020
1021 InternalEventHandler(Event event) {
1022 this.event = event;
1023 }
1024
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001025 @Override
sanghob35a6192015-04-01 13:05:26 -07001026 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001027 try {
1028 // TODO We should also change SR routing and PW to listen to TopologyEvents
1029 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1030 event.type() == LinkEvent.Type.LINK_UPDATED) {
1031 linkHandler.processLinkAdded((Link) event.subject());
1032 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1033 linkHandler.processLinkRemoved((Link) event.subject());
1034 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1035 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1036 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1037 DeviceId deviceId = ((Device) event.subject()).id();
1038 if (deviceService.isAvailable(deviceId)) {
1039 log.info("** DEVICE UP Processing device event {} "
1040 + "for available device {}",
1041 event.type(), ((Device) event.subject()).id());
1042 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001043 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001044 log.info(" ** DEVICE DOWN Processing device event {}"
1045 + " for unavailable device {}",
1046 event.type(), ((Device) event.subject()).id());
1047 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001048 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001049 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1050 // typically these calls come when device is added first time
1051 // so port filtering rules are handled at the device_added event.
1052 // port added calls represent all ports on the device,
1053 // enabled or not.
1054 log.trace("** PORT ADDED {}/{} -> {}",
1055 ((DeviceEvent) event).subject().id(),
1056 ((DeviceEvent) event).port().number(),
1057 event.type());
1058 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1059 // these calls happen for every subsequent event
1060 // ports enabled, disabled, switch goes away, comes back
1061 log.info("** PORT UPDATED {}/{} -> {}",
1062 event.subject(),
1063 ((DeviceEvent) event).port(),
1064 event.type());
1065 processPortUpdated(((Device) event.subject()),
1066 ((DeviceEvent) event).port());
1067 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1068 // Process topology event, needed for all modules relying on
1069 // topology service for path computation
1070 TopologyEvent topologyEvent = (TopologyEvent) event;
1071 log.info("Processing topology event {}, topology age {}, reasons {}",
1072 event.type(), topologyEvent.subject().time(),
1073 topologyEvent.reasons().size());
1074 topologyHandler.processTopologyChange(topologyEvent.reasons());
1075 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1076 hostHandler.processHostAddedEvent((HostEvent) event);
1077 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1078 hostHandler.processHostMovedEvent((HostEvent) event);
1079 routeHandler.processHostMovedEvent((HostEvent) event);
1080 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1081 hostHandler.processHostRemovedEvent((HostEvent) event);
1082 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1083 hostHandler.processHostUpdatedEvent((HostEvent) event);
1084 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1085 routeHandler.processRouteAdded((RouteEvent) event);
1086 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1087 routeHandler.processRouteUpdated((RouteEvent) event);
1088 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1089 routeHandler.processRouteRemoved((RouteEvent) event);
1090 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1091 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1092 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1093 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1094 event.type() == McastEvent.Type.SINKS_ADDED ||
1095 event.type() == McastEvent.Type.SINKS_REMOVED ||
1096 event.type() == McastEvent.Type.ROUTE_ADDED ||
1097 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1098 mcastHandler.processMcastEvent((McastEvent) event);
1099 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1100 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1101 Class configClass = netcfgEvent.configClass();
1102 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1103 appCfgHandler.processAppConfigAdded(netcfgEvent);
1104 log.info("App config event .. configuring network");
1105 cfgListener.configureNetwork();
1106 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1107 log.info("Segment Routing Device Config added for {}", event.subject());
1108 cfgListener.configureNetwork();
1109 } else if (configClass.equals(XConnectConfig.class)) {
1110 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1111 } else if (configClass.equals(InterfaceConfig.class)) {
1112 log.info("Interface Config added for {}", event.subject());
1113 cfgListener.configureNetwork();
1114 } else {
1115 log.error("Unhandled config class: {}", configClass);
1116 }
1117 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1118 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1119 Class configClass = netcfgEvent.configClass();
1120 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1121 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1122 log.info("App config event .. configuring network");
1123 cfgListener.configureNetwork();
1124 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1125 log.info("Segment Routing Device Config updated for {}", event.subject());
1126 createOrUpdateDeviceConfiguration();
1127 } else if (configClass.equals(XConnectConfig.class)) {
1128 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1129 } else if (configClass.equals(InterfaceConfig.class)) {
1130 log.info("Interface Config updated for {}", event.subject());
1131 createOrUpdateDeviceConfiguration();
1132 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1133 (InterfaceConfig) netcfgEvent.prevConfig().get());
1134 } else {
1135 log.error("Unhandled config class: {}", configClass);
1136 }
1137 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1138 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1139 Class configClass = netcfgEvent.configClass();
1140 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1141 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1142 log.info("App config event .. configuring network");
1143 cfgListener.configureNetwork();
1144 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1145 // TODO Handle sr device config removal
1146 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1147 } else if (configClass.equals(XConnectConfig.class)) {
1148 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1149 } else if (configClass.equals(InterfaceConfig.class)) {
1150 // TODO Handle interface removal
1151 log.info("InterfaceConfig removal is not handled in current implementation");
1152 } else {
1153 log.error("Unhandled config class: {}", configClass);
1154 }
1155 } else {
1156 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001157 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001158 } catch (Exception e) {
1159 log.error("SegmentRouting event handler thread thrown an exception: {}",
1160 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001161 }
sanghob35a6192015-04-01 13:05:26 -07001162 }
1163 }
1164
Saurav Das45f48152018-01-18 12:07:33 -08001165 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001166 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001167
1168 // NOTE: Punt ARP/NDP even when the device is not configured.
1169 // Host learning without network config is required for CORD config generator.
1170 routingRulePopulator.populateIpPunts(device.id());
1171 routingRulePopulator.populateArpNdpPunts(device.id());
1172
Charles Chan0b4e6182015-11-03 10:42:14 -08001173 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001174 log.warn("Device configuration unavailable. Device {} will be "
1175 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001176 return;
1177 }
Charles Chan2199c302016-04-23 17:36:10 -07001178 processDeviceAddedInternal(device.id());
1179 }
1180
1181 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001182 // Irrespective of whether the local is a MASTER or not for this device,
1183 // we need to create a SR-group-handler instance. This is because in a
1184 // multi-instance setup, any instance can initiate forwarding/next-objectives
1185 // for any switch (even if this instance is a SLAVE or not even connected
1186 // to the switch). To handle this, a default-group-handler instance is necessary
1187 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001188 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1189 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001190 DefaultGroupHandler groupHandler;
1191 try {
1192 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001193 createGroupHandler(deviceId,
1194 appId,
1195 deviceConfiguration,
1196 linkService,
1197 flowObjectiveService,
1198 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001199 } catch (DeviceConfigNotFoundException e) {
1200 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1201 return;
1202 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001203 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001204 deviceId);
1205 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001206 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001207
Charles Chan2199c302016-04-23 17:36:10 -07001208 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001209 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001210 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001211 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001212 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001213 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001214 }
Charles Chan5270ed02016-01-30 23:22:37 -08001215
Charles Chan03a73e02016-10-24 14:52:01 -07001216 appCfgHandler.init(deviceId);
Charles Chan2ff1bac2018-03-29 16:03:41 -07001217 hostHandler.init(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001218 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001219 }
1220
Saurav Das80980c72016-03-23 11:22:49 -07001221 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001222 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001223 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001224 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001225 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001226 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001227 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001228 portNextObjStore.entrySet().stream()
1229 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001230 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001231 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001232
Saurav Dasceccf242017-08-03 18:30:35 -07001233 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1234 if (gh != null) {
1235 gh.shutdown();
1236 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001237 // Note that a switch going down is associated with all of its links
1238 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001239 // while the link-downs are ignored. We cannot rely on the ordering of
1240 // events - i.e we cannot expect all link-downs to come before the
1241 // switch down - so we purge all seen-links for the switch before
1242 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001243 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001244 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001245 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001246 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001247
1248 // Cleanup all internal groupHandler stores for this device. Should be
1249 // done after all rerouting or rehashing has been completed
1250 groupHandlerMap.entrySet()
1251 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001252 }
1253
Saurav Das1a129a02016-11-18 15:21:57 -08001254 private void processPortUpdated(Device device, Port port) {
1255 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1256 log.warn("Device configuration uploading. Not handling port event for"
1257 + "dev: {} port: {}", device.id(), port.number());
1258 return;
1259 }
Saurav Das018605f2017-02-18 14:05:44 -08001260
1261 if (!mastershipService.isLocalMaster(device.id())) {
1262 log.debug("Not master for dev:{} .. not handling port updated event"
1263 + "for port {}", device.id(), port.number());
1264 return;
1265 }
1266
1267 // first we handle filtering rules associated with the port
1268 if (port.isEnabled()) {
1269 log.info("Switchport {}/{} enabled..programming filters",
1270 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001271 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001272 } else {
1273 log.info("Switchport {}/{} disabled..removing filters",
1274 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001275 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001276 }
Saurav Das1a129a02016-11-18 15:21:57 -08001277
1278 // portUpdated calls are for ports that have gone down or up. For switch
1279 // to switch ports, link-events should take care of any re-routing or
1280 // group editing necessary for port up/down. Here we only process edge ports
1281 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001282 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1283 VlanId untaggedVlan = getUntaggedVlanId(cp);
1284 VlanId nativeVlan = getNativeVlanId(cp);
1285 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001286
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001287 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001288 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001289 + "dev/port: {}/{}", device.id(), port.number());
1290 return;
1291 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001292 if (untaggedVlan != null) {
1293 processEdgePort(device, port, untaggedVlan, true);
1294 }
1295 if (nativeVlan != null) {
1296 processEdgePort(device, port, nativeVlan, true);
1297 }
1298 if (!taggedVlans.isEmpty()) {
1299 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1300 }
Saurav Das1a129a02016-11-18 15:21:57 -08001301 }
1302
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001303 private void processEdgePort(Device device, Port port, VlanId vlanId,
1304 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001305 boolean portUp = port.isEnabled();
1306 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001307 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001308 port.number(), vlanId);
Charles Chan47933752017-11-30 15:37:50 -08001309 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001310 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001311 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001312 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001313 }
1314
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001315 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001316 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001317 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001318 } else {
1319 log.warn("Group handler not found for dev:{}. Not handling edge port"
1320 + " {} event for port:{}", device.id(),
1321 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001322 }
1323 }
sangho1e575652015-05-14 00:39:53 -07001324
Charles Chan27fe1a52017-10-20 16:06:55 -07001325 private void createOrUpdateDeviceConfiguration() {
1326 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001327 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001328 deviceConfiguration = new DeviceConfiguration(this);
1329 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001330 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001331 deviceConfiguration.updateConfig();
1332 }
1333 }
1334
Pier Ventre10bd8d12016-11-26 21:05:22 -08001335 /**
1336 * Registers the given connect point with the NRS, this is necessary
1337 * to receive the NDP and ARP packets from the NRS.
1338 *
1339 * @param portToRegister connect point to register
1340 */
1341 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001342 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001343 portToRegister,
1344 neighbourHandler,
1345 appId
1346 );
1347 }
1348
Charles Chand6832882015-10-05 17:50:33 -07001349 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001350 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001351 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001352
Charles Chane849c192016-01-11 18:28:54 -08001353 /**
1354 * Constructs the internal network config listener.
1355 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001356 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001357 */
Charles Chan65238242017-06-22 18:03:14 -07001358 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001359 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001360 }
1361
Charles Chane849c192016-01-11 18:28:54 -08001362 /**
1363 * Reads network config and initializes related data structure accordingly.
1364 */
Charles Chan47933752017-11-30 15:37:50 -08001365 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001366 log.info("Configuring network ...");
Charles Chan27fe1a52017-10-20 16:06:55 -07001367 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001368
Charles Chan2c15aca2016-11-09 20:51:44 -08001369 arpHandler = new ArpHandler(srManager);
1370 icmpHandler = new IcmpHandler(srManager);
1371 ipHandler = new IpHandler(srManager);
1372 routingRulePopulator = new RoutingRulePopulator(srManager);
1373 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001374
1375 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1376 groupHandlerMap, tunnelStore);
1377 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1378 flowObjectiveService,
1379 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001380 // add a small delay to absorb multiple network config added notifications
1381 if (!programmingScheduled.get()) {
Saurav Dase7f51012018-02-09 17:26:45 -08001382 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das7bcbe702017-06-13 15:35:54 -07001383 programmingScheduled.set(true);
Charles Chan9b7217c2018-04-05 16:31:15 -07001384 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001385 }
Charles Chan2199c302016-04-23 17:36:10 -07001386 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001387 }
1388
Charles Chand6832882015-10-05 17:50:33 -07001389 @Override
1390 public void event(NetworkConfigEvent event) {
Charles Chan7a888e82018-03-21 16:57:47 -07001391 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1392 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1393 switch (event.type()) {
1394 case CONFIG_ADDED:
1395 case CONFIG_UPDATED:
1396 case CONFIG_REMOVED:
1397 log.trace("Schedule Network Config event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001398 mainEventExecutor.execute(new InternalEventHandler(event));
Charles Chan7a888e82018-03-21 16:57:47 -07001399 break;
1400 default:
1401 break;
Charles Chand6832882015-10-05 17:50:33 -07001402 }
1403 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001404
Charles Chan50443e82018-01-03 16:26:32 -08001405 @Override
1406 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001407 if (event.type() == CONFIG_REGISTERED ||
1408 event.type() == CONFIG_UNREGISTERED) {
1409 log.debug("Ignore event {} due to type mismatch", event);
1410 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001411 }
Saurav Dase7f51012018-02-09 17:26:45 -08001412
1413 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1414 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1415 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001416 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001417 log.debug("Ignore event {} due to class mismatch", event);
1418 return false;
1419 }
1420
1421 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001422 }
1423
Saurav Das7bcbe702017-06-13 15:35:54 -07001424 private final class ConfigChange implements Runnable {
1425 @Override
1426 public void run() {
1427 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001428 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001429 for (Device device : deviceService.getDevices()) {
1430 processDeviceAdded(device);
1431 }
1432 defaultRoutingHandler.startPopulationProcess();
1433 }
1434 }
Charles Chand6832882015-10-05 17:50:33 -07001435 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001436
Charles Chan7a888e82018-03-21 16:57:47 -07001437 private class InternalLinkListener implements LinkListener {
1438 @Override
1439 public void event(LinkEvent event) {
1440 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1441 event.type() == LinkEvent.Type.LINK_UPDATED ||
1442 event.type() == LinkEvent.Type.LINK_REMOVED) {
1443 log.trace("Schedule Link event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001444 mainEventExecutor.execute(new InternalEventHandler(event));
Charles Chan7a888e82018-03-21 16:57:47 -07001445 }
1446 }
1447 }
1448
1449 private class InternalDeviceListener implements DeviceListener {
1450 @Override
1451 public void event(DeviceEvent event) {
1452 switch (event.type()) {
1453 case DEVICE_ADDED:
1454 case PORT_UPDATED:
1455 case PORT_ADDED:
1456 case DEVICE_UPDATED:
1457 case DEVICE_AVAILABILITY_CHANGED:
1458 log.trace("Schedule Device event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001459 mainEventExecutor.execute(new InternalEventHandler(event));
Charles Chan7a888e82018-03-21 16:57:47 -07001460 break;
1461 default:
1462 }
1463 }
1464 }
1465
1466 private class InternalTopologyListener implements TopologyListener {
1467 @Override
1468 public void event(TopologyEvent event) {
1469 switch (event.type()) {
1470 case TOPOLOGY_CHANGED:
1471 log.trace("Schedule Topology event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001472 mainEventExecutor.execute(new InternalEventHandler(event));
Charles Chan7a888e82018-03-21 16:57:47 -07001473 break;
1474 default:
1475 }
1476 }
1477 }
1478
Charles Chan68aa62d2015-11-09 16:37:23 -08001479 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001480 @Override
1481 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001482 switch (event.type()) {
1483 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001484 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001485 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001486 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001487 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001488 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001489 break;
1490 default:
1491 log.warn("Unsupported host event type: {}", event.type());
1492 break;
1493 }
1494 }
1495 }
1496
Charles Chand55e84d2016-03-30 17:54:24 -07001497 private class InternalMcastListener implements McastListener {
1498 @Override
1499 public void event(McastEvent event) {
1500 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001501 case SOURCES_ADDED:
1502 case SOURCES_REMOVED:
1503 case SINKS_ADDED:
1504 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001505 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001506 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001507 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001508 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001509 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001510 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001511 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001512 break;
1513 }
1514 }
1515 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001516
Charles Chan03a73e02016-10-24 14:52:01 -07001517 private class InternalRouteEventListener implements RouteListener {
1518 @Override
1519 public void event(RouteEvent event) {
1520 switch (event.type()) {
1521 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001522 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001523 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001524 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001525 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001526 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001527 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001528 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001529 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001530 break;
1531 }
1532 }
1533 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001534
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001535 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1536 try {
1537 Set<Interface> intfs = conf.getInterfaces();
1538 Set<Interface> prevIntfs = prevConf.getInterfaces();
1539
1540 // Now we only handle one interface config at each port.
1541 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1542 log.warn("Interface update aborted - one at a time is allowed, " +
1543 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1544 return;
1545 }
1546
1547 Interface intf = intfs.stream().findFirst().get();
1548 Interface prevIntf = prevIntfs.stream().findFirst().get();
1549
1550 DeviceId deviceId = intf.connectPoint().deviceId();
1551 PortNumber portNum = intf.connectPoint().port();
1552
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001553 removeSubnetConfig(prevIntf.connectPoint(),
1554 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1555 new HashSet<>(intf.ipAddressesList())));
1556
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001557 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1558 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1559 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1560 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1561 // Update filtering objective and L2IG group bucket
1562 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1563 } else {
1564 // RemoveVlanNative
1565 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1566 }
1567 }
1568
1569 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1570 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1571 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1572 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1573 // Update filtering objective and L2IG group bucket
1574 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1575 } else {
1576 // RemoveVlanUntagged
1577 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1578 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001579 }
1580
1581 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1582 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001583 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1584 .filter(i -> !intf.vlanUntagged().equals(i))
1585 .filter(i -> !intf.vlanNative().equals(i))
1586 .forEach(vlanId -> updateVlanConfigInternal(
1587 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001588 }
1589
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001590 if (!intf.vlanNative().equals(VlanId.NONE)
1591 && !prevIntf.vlanNative().equals(intf.vlanNative())
1592 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1593 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1594 // Update filtering objective and L2IG group bucket
1595 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1596 } else {
1597 // AddVlanNative
1598 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1599 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001600 }
1601
1602 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1603 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001604 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1605 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1606 .filter(i -> !prevIntf.vlanNative().equals(i))
1607 .forEach(vlanId -> updateVlanConfigInternal(
1608 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001609 );
1610 }
1611
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001612 if (!intf.vlanUntagged().equals(VlanId.NONE)
1613 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1614 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1615 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1616 // Update filtering objective and L2IG group bucket
1617 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1618 } else {
1619 // AddVlanUntagged
1620 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1621 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001622 }
1623 addSubnetConfig(prevIntf.connectPoint(),
1624 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1625 new HashSet<>(prevIntf.ipAddressesList())));
1626 } catch (ConfigException e) {
1627 log.error("Error in configuration");
1628 }
1629 }
1630
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001631 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1632 VlanId vlanId, boolean pushVlan) {
1633 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1634 if (grpHandler == null) {
1635 log.warn("Failed to retrieve group handler for device {}", deviceId);
1636 return;
1637 }
1638
1639 // Update filtering objective for a single port
1640 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1641 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1642
1643 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1644 // Update L2IG bucket of the port
1645 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1646 } else {
1647 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1648 }
1649 }
1650
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001651 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1652 VlanId vlanId, boolean pushVlan, boolean install) {
1653 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1654 if (grpHandler == null) {
1655 log.warn("Failed to retrieve group handler for device {}", deviceId);
1656 return;
1657 }
1658
1659 // Update filtering objective for a single port
1660 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1661
1662 // Update filtering objective for multicast ingress port
1663 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1664
1665 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1666
1667 if (nextId != -1 && !install) {
1668 // Update next objective for a single port as an output port
1669 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001670 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001671 // Remove L2 Bridging rule and L3 Unicast rule to the host
1672 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1673 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1674 // only if there is no port configured on that VLAN ID
1675 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1676 // Remove broadcast forwarding rule for the VLAN
1677 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1678 // Remove L2FG for VLAN
1679 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1680 } else {
1681 // Remove L2IG of the port
1682 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1683 }
1684 } else if (install) {
1685 if (nextId != -1) {
1686 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001687 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001688 } else {
1689 // Create L2FG for VLAN
1690 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1691 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1692 }
1693 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1694 } else {
1695 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1696 }
1697 }
1698
1699 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1700 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1701 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1702
1703 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1704 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1705 .filter(intf -> !intf.connectPoint().equals(cp))
1706 .flatMap(intf -> intf.ipAddressesList().stream())
1707 .collect(Collectors.toSet());
1708 // 1. Partial subnet population
1709 // Remove routing rules for removed subnet from previous configuration,
1710 // which does not also exist in other interfaces in the same device
1711 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1712 .map(InterfaceIpAddress::subnetAddress)
1713 .collect(Collectors.toSet());
1714
1715 defaultRoutingHandler.revokeSubnet(
1716 ipPrefixSet.stream()
1717 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1718 .collect(Collectors.toSet()));
1719
1720 // 2. Interface IP punts
1721 // Remove IP punts for old Intf address
1722 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1723 .map(InterfaceIpAddress::ipAddress)
1724 .collect(Collectors.toSet());
1725 ipAddressSet.stream()
1726 .map(InterfaceIpAddress::ipAddress)
1727 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1728 .forEach(interfaceIpAddress ->
1729 routingRulePopulator.revokeSingleIpPunts(
1730 cp.deviceId(), interfaceIpAddress));
1731
1732 // 3. Host unicast routing rule
1733 // Remove unicast routing rule
1734 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1735 }
1736
1737 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1738 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1739 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1740
1741 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1742 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1743 .filter(intf -> !intf.connectPoint().equals(cp))
1744 .flatMap(intf -> intf.ipAddressesList().stream())
1745 .collect(Collectors.toSet());
1746 // 1. Partial subnet population
1747 // Add routing rules for newly added subnet, which does not also exist in
1748 // other interfaces in the same device
1749 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1750 .map(InterfaceIpAddress::subnetAddress)
1751 .collect(Collectors.toSet());
1752
1753 defaultRoutingHandler.populateSubnet(
1754 Collections.singleton(cp),
1755 ipPrefixSet.stream()
1756 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1757 .collect(Collectors.toSet()));
1758
1759 // 2. Interface IP punts
1760 // Add IP punts for new Intf address
1761 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1762 .map(InterfaceIpAddress::ipAddress)
1763 .collect(Collectors.toSet());
1764 ipAddressSet.stream()
1765 .map(InterfaceIpAddress::ipAddress)
1766 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1767 .forEach(interfaceIpAddress ->
1768 routingRulePopulator.populateSingleIpPunts(
1769 cp.deviceId(), interfaceIpAddress));
1770
1771 // 3. Host unicast routing rule
1772 // Add unicast routing rule
1773 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1774 }
sanghob35a6192015-04-01 13:05:26 -07001775}