blob: a41c58da250a25240187039f0f9fdfdca3900220 [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;
Saurav Das201762d2018-04-21 17:19:48 -070041import org.onosproject.cluster.ClusterEvent;
42import org.onosproject.cluster.ClusterEventListener;
Pier Luigieba73a02018-01-16 10:47:50 +010043import org.onosproject.cluster.ClusterService;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -070044import org.onosproject.cluster.LeadershipService;
Pier96f63cb2018-04-17 16:29:56 +020045import org.onosproject.cluster.NodeId;
sanghob35a6192015-04-01 13:05:26 -070046import org.onosproject.core.ApplicationId;
47import org.onosproject.core.CoreService;
48import org.onosproject.event.Event;
Charles Chan50bb6ef2018-04-18 18:41:05 -070049import org.onosproject.mastership.MastershipEvent;
50import org.onosproject.mastership.MastershipListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070051import org.onosproject.mastership.MastershipService;
Pier3ee24552018-03-14 16:47:32 -070052import org.onosproject.mcast.api.McastEvent;
53import org.onosproject.mcast.api.McastListener;
54import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Saurav Das45f48152018-01-18 12:07:33 -080071import org.onosproject.net.device.DeviceAdminService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070072import org.onosproject.net.device.DeviceEvent;
73import org.onosproject.net.device.DeviceListener;
74import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080075import org.onosproject.net.flow.TrafficSelector;
76import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070077import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chand5814aa2018-08-19 19:21:46 -070078import org.onosproject.net.flowobjective.NextObjective;
Charles Chan68aa62d2015-11-09 16:37:23 -080079import org.onosproject.net.host.HostEvent;
80import org.onosproject.net.host.HostListener;
Charles Chanff79dd92018-06-01 16:33:48 -070081import org.onosproject.net.host.HostProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080082import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070083import org.onosproject.net.host.InterfaceIpAddress;
Pier96f63cb2018-04-17 16:29:56 +020084import org.onosproject.net.intent.WorkPartitionService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070085import org.onosproject.net.intf.Interface;
86import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080087import org.onosproject.net.link.LinkEvent;
88import org.onosproject.net.link.LinkListener;
89import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070090import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080091import org.onosproject.net.packet.InboundPacket;
92import org.onosproject.net.packet.PacketContext;
93import org.onosproject.net.packet.PacketProcessor;
94import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010095import org.onosproject.net.topology.TopologyEvent;
96import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070097import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070098import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070099import org.onosproject.routeservice.RouteEvent;
100import org.onosproject.routeservice.RouteListener;
101import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700102import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
103import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800104import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700105import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700106import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700107import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700108import org.onosproject.segmentrouting.grouphandler.DestinationSet;
109import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100110import org.onosproject.segmentrouting.mcast.McastHandler;
111import org.onosproject.segmentrouting.mcast.McastRole;
Pier3e793752018-04-19 16:47:06 +0200112import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700116import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800117
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800118import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700119import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800121import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
122
Saurav Das7bcbe702017-06-13 15:35:54 -0700123import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700124import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Pier3e793752018-04-19 16:47:06 +0200125import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700126import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800127import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700128import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chanc7b3c452018-06-19 20:31:57 -0700129import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700130import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700131import org.onosproject.store.service.EventuallyConsistentMap;
132import org.onosproject.store.service.EventuallyConsistentMapBuilder;
133import org.onosproject.store.service.StorageService;
134import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800135import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700136import org.slf4j.Logger;
137import org.slf4j.LoggerFactory;
138
Saurav Das201762d2018-04-21 17:19:48 -0700139import java.time.Instant;
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700140import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800141import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800142import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800143import java.util.HashSet;
144import java.util.List;
145import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800146import java.util.Optional;
147import java.util.Set;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200148import java.util.concurrent.CompletableFuture;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800149import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200150import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan07f15f22018-05-08 21:35:50 -0700151import java.util.concurrent.ExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800152import java.util.concurrent.Executors;
153import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800154import java.util.concurrent.TimeUnit;
155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.stream.Collectors;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700157import java.util.stream.IntStream;
sanghob35a6192015-04-01 13:05:26 -0700158
Charles Chan3e783d02016-02-26 22:19:52 -0800159import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800160import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700161import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
163import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800164
Charles Chane849c192016-01-11 18:28:54 -0800165/**
166 * Segment routing manager.
167 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700168@Service
169@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700170public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700171
Charles Chan2c15aca2016-11-09 20:51:44 -0800172 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700173 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700176 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800179 private NeighbourResolutionService neighbourResolutionService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100182 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700185 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700188 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanff79dd92018-06-01 16:33:48 -0700191 HostProbingService probingService;
Charles Chan47933752017-11-30 15:37:50 -0800192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100194 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800197 DeviceAdminService deviceAdminService;
198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800200 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100203 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700204
Charles Chan5270ed02016-01-30 23:22:37 -0800205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800206 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700207
208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800209 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700210
211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100212 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700213
214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800215 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700216
217 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700218 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800219
220 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800221 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800222
Saurav Das80980c72016-03-23 11:22:49 -0700223 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800224 public InterfaceService interfaceService;
225
Pier Luigieba73a02018-01-16 10:47:50 +0100226 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
227 public ClusterService clusterService;
228
229 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier96f63cb2018-04-17 16:29:56 +0200230 public WorkPartitionService workPartitionService;
Pier Luigieba73a02018-01-16 10:47:50 +0100231
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700232 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
233 public LeadershipService leadershipService;
234
Charles Chanc7b3c452018-06-19 20:31:57 -0700235 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
236 public XconnectService xconnectService;
237
Charles Chan47933752017-11-30 15:37:50 -0800238 @Property(name = "activeProbing", boolValue = true,
239 label = "Enable active probing to discover dual-homed hosts.")
240 boolean activeProbing = true;
241
Saurav Das9a554292018-04-27 18:42:30 -0700242 @Property(name = "singleHomedDown", boolValue = false,
243 label = "Enable administratively taking down single-homed hosts "
244 + "when all uplinks are gone")
245 boolean singleHomedDown = false;
246
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700247 @Property(name = "respondToUnknownHosts", boolValue = true,
248 label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
249 boolean respondToUnknownHosts = true;
250
Charles Chanb67dfdd2018-07-24 16:40:35 -0700251 @Property(name = "routeDoubleTaggedHosts", boolValue = false,
252 label = "Program flows and groups to pop and route double tagged hosts")
253 boolean routeDoubleTaggedHosts = false;
Charles Chan57465d32018-07-19 14:55:31 -0700254
Saurav Das09c2c4d2018-08-13 15:34:26 -0700255 private static final int DEFAULT_INTERNAL_VLAN = 4094;
256 @Property(name = "defaultInternalVlan", intValue = DEFAULT_INTERNAL_VLAN,
257 label = "internal vlan assigned by default to unconfigured ports")
258 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN;
259
260 private static final int PW_TRANSPORT_VLAN = 4090;
261 @Property(name = "pwTransportVlan", intValue = PW_TRANSPORT_VLAN,
262 label = "vlan used for transport of pseudowires between switches")
263 private int pwTransportVlan = PW_TRANSPORT_VLAN;
264
Charles Chan03a73e02016-10-24 14:52:01 -0700265 ArpHandler arpHandler = null;
266 IcmpHandler icmpHandler = null;
267 IpHandler ipHandler = null;
268 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700269 ApplicationId appId;
270 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700271
Charles Chan03a73e02016-10-24 14:52:01 -0700272 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700273 private TunnelHandler tunnelHandler = null;
274 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700275 private InternalPacketProcessor processor = null;
276 private InternalLinkListener linkListener = null;
277 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700278 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100279 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800280 McastHandler mcastHandler = null;
281 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800282 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800283 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800284 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800285 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100286 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800287 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700288 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
289 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700290 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100291 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700292 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das201762d2018-04-21 17:19:48 -0700293 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200294 //Completable future for network configuration process to buffer config events handling during activation
295 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan10b2fee2018-04-21 00:44:29 -0700296 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sanghob35a6192015-04-01 13:05:26 -0700297
Charles Chan9b7217c2018-04-05 16:31:15 -0700298 // Handles device, link, topology and network config events
Charles Chan50bb6ef2018-04-18 18:41:05 -0700299 private ScheduledExecutorService mainEventExecutor;
sanghob35a6192015-04-01 13:05:26 -0700300
Charles Chan50bb6ef2018-04-18 18:41:05 -0700301 // Handles host, route and mcast events respectively
302 private ScheduledExecutorService hostEventExecutor;
303 private ScheduledExecutorService routeEventExecutor;
304 private ScheduledExecutorService mcastEventExecutor;
Charles Chan07f15f22018-05-08 21:35:50 -0700305 private ExecutorService packetExecutor;
Charles Chan9b7217c2018-04-05 16:31:15 -0700306
307 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800308 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700309 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700310 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800311 */
Charles Chan47933752017-11-30 15:37:50 -0800312 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700313 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800314 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700315 * Per device next objective ID store with (device id + vlanid) as key.
316 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800317 */
Charles Chan47933752017-11-30 15:37:50 -0800318 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800319 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800320 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700321 * Per device next objective ID store with (device id + port + treatment + meta) as key.
322 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800323 */
Charles Chan47933752017-11-30 15:37:50 -0800324 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800325 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800326
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700327 /**
328 * Per port dummy VLAN ID store with (connect point + ip address) as key.
329 * Used to keep track on dummy VLAN ID allocation.
330 */
331 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
332 dummyVlanIdStore = null;
333
Saurav Das4ce45962015-11-24 23:21:05 -0800334 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
335 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700336
Saurav Das7bcbe702017-06-13 15:35:54 -0700337 private AtomicBoolean programmingScheduled = new AtomicBoolean();
338
Charles Chand55e84d2016-03-30 17:54:24 -0700339 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700340 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
341 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700342 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700343 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800344 public SegmentRoutingDeviceConfig createConfig() {
345 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700346 }
347 };
Pier Ventref34966c2016-11-07 16:21:04 -0800348
Charles Chand55e84d2016-03-30 17:54:24 -0700349 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700350 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
351 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700352 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800353 @Override
354 public SegmentRoutingAppConfig createConfig() {
355 return new SegmentRoutingAppConfig();
356 }
357 };
Pier Ventref34966c2016-11-07 16:21:04 -0800358
Charles Chanfc5c7802016-05-17 13:13:55 -0700359 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
360 new ConfigFactory<ApplicationId, XConnectConfig>(
361 SubjectFactories.APP_SUBJECT_FACTORY,
362 XConnectConfig.class, "xconnect") {
363 @Override
364 public XConnectConfig createConfig() {
365 return new XConnectConfig();
366 }
367 };
Pier Ventref34966c2016-11-07 16:21:04 -0800368
Charles Chand55e84d2016-03-30 17:54:24 -0700369 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700370 new ConfigFactory<ApplicationId, McastConfig>(
371 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700372 McastConfig.class, "multicast") {
373 @Override
374 public McastConfig createConfig() {
375 return new McastConfig();
376 }
377 };
378
Charles Chan116188d2016-02-18 14:22:42 -0800379 /**
380 * Segment Routing App ID.
381 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800382 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das0e99e2b2015-10-28 12:39:42 -0700383
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700384 /**
385 * Minumum and maximum value of dummy VLAN ID to be allocated.
386 */
387 public static final int MIN_DUMMY_VLAN_ID = 2;
388 public static final int MAX_DUMMY_VLAN_ID = 4093;
389
Saurav Das9a554292018-04-27 18:42:30 -0700390 Instant lastEdgePortEvent = Instant.EPOCH;
391
sanghob35a6192015-04-01 13:05:26 -0700392 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800393 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800394 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700395
Charles Chan50bb6ef2018-04-18 18:41:05 -0700396 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
397 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
398 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
399 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan07f15f22018-05-08 21:35:50 -0700400 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chan50bb6ef2018-04-18 18:41:05 -0700401
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700402 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700403 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700404 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700405 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700406 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700407 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700408 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700409 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700410 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700411
Charles Chan59cc16d2017-02-02 16:20:42 -0800412 log.debug("Creating EC map vlannextobjectivestore");
413 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
414 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
415 vlanNextObjStore = vlanNextObjMapBuilder
416 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700417 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700418 .withTimestampProvider((k, v) -> new WallClockTimestamp())
419 .build();
420
Saurav Das4ce45962015-11-24 23:21:05 -0800421 log.debug("Creating EC map subnetnextobjectivestore");
422 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
423 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
424 portNextObjStore = portNextObjMapBuilder
425 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700426 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800427 .withTimestampProvider((k, v) -> new WallClockTimestamp())
428 .build();
429
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700430 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
431 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
432 dummyVlanIdStore = dummyVlanIdMapBuilder
433 .withName("dummyvlanidstore")
434 .withSerializer(createSerializer())
435 .withTimestampProvider((k, v) -> new WallClockTimestamp())
436 .build();
437
sangho0b2b6d12015-05-20 22:16:38 -0700438 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
439 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700440 tunnelStore = tunnelMapBuilder
441 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700442 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700443 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700444 .build();
445
446 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
447 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700448 policyStore = policyMapBuilder
449 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700450 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700451 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700452 .build();
453
Saurav Das80980c72016-03-23 11:22:49 -0700454 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800455 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700456 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800457 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800458 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
459 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700460 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800461 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700462 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800463 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800464 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
465 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800466 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
467 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700468 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700469 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700470 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
471 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800472 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
473 "staleLinkAge", "15000");
474 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
475 "allowDuplicateIps", "false");
Yi Tsengfe13f3e2018-08-19 03:09:54 +0800476 // For P4 switches
477 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chanc76685f2018-08-30 17:30:45 -0700478 "fallbackFlowPollFrequency", "4");
Yi Tsengfe13f3e2018-08-19 03:09:54 +0800479 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chanc76685f2018-08-30 17:30:45 -0700480 "fallbackGroupPollFrequency", "3");
Charles Chan47933752017-11-30 15:37:50 -0800481 compCfgService.registerProperties(getClass());
482 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700483
Charles Chanb8e10c82015-10-14 11:24:40 -0700484 processor = new InternalPacketProcessor();
485 linkListener = new InternalLinkListener();
486 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700487 appCfgHandler = new AppConfigHandler(this);
488 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700489 mcastHandler = new McastHandler(this);
490 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800491 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700492 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800493 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800494 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100495 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700496
Charles Chan3e783d02016-02-26 22:19:52 -0800497 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700498 cfgService.registerConfigFactory(deviceConfigFactory);
499 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700500 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700501 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800502 log.info("Configuring network before adding listeners");
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200503
Charles Chan132393a2018-01-04 14:26:07 -0800504 cfgListener.configureNetwork();
505
Charles Chan5270ed02016-01-30 23:22:37 -0800506 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700507 packetService.addProcessor(processor, PacketProcessor.director(2));
508 linkService.addListener(linkListener);
509 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700510 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700511 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100512 topologyService.addListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700513 mastershipService.addListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700514 clusterService.addListener(clusterListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700515
Charles Chanb39777c2018-03-09 15:53:44 -0800516 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800517 l2TunnelHandler.init();
518
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200519 networkConfigCompletion.whenComplete((value, ex) -> {
520 //setting to null for easier fall through
521 networkConfigCompletion = null;
522 //process all queued events
Charles Chan10b2fee2018-04-21 00:44:29 -0700523 queuedEvents.forEach(event -> {
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200524 mainEventExecutor.execute(new InternalEventHandler(event));
525 });
526 });
527
sanghob35a6192015-04-01 13:05:26 -0700528 log.info("Started");
529 }
530
Saurav Das45f48152018-01-18 12:07:33 -0800531 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700532 return new KryoNamespace.Builder()
533 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700534 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800535 VlanNextObjectiveStoreKey.class,
536 DestinationSet.class,
Andreas Pantelopoulos67e09ae2018-05-29 13:11:14 -0700537 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800538 NextNeighbors.class,
539 Tunnel.class,
540 DefaultTunnel.class,
541 Policy.class,
542 TunnelPolicy.class,
543 Policy.Type.class,
544 PortNextObjectiveStoreKey.class,
545 XConnectStoreKey.class,
546 L2Tunnel.class,
547 L2TunnelPolicy.class,
548 DefaultL2Tunnel.class,
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700549 DefaultL2TunnelPolicy.class,
550 DummyVlanIdStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700551 );
552 }
553
sanghob35a6192015-04-01 13:05:26 -0700554 @Deactivate
555 protected void deactivate() {
Charles Chan50bb6ef2018-04-18 18:41:05 -0700556 mainEventExecutor.shutdown();
557 hostEventExecutor.shutdown();
558 routeEventExecutor.shutdown();
559 mcastEventExecutor.shutdown();
Charles Chan07f15f22018-05-08 21:35:50 -0700560 packetExecutor.shutdown();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700561
Ray Milkey749996b2018-05-11 09:59:19 -0700562 mainEventExecutor = null;
563 hostEventExecutor = null;
564 routeEventExecutor = null;
565 mcastEventExecutor = null;
566 packetExecutor = null;
567
Charles Chand6832882015-10-05 17:50:33 -0700568 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700569 cfgService.unregisterConfigFactory(deviceConfigFactory);
570 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700571 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700572 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800573 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700574
Charles Chanc7a8a682017-06-19 00:43:31 -0700575 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700576 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700577 linkService.removeListener(linkListener);
578 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700579 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700580 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100581 topologyService.removeListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700582 mastershipService.removeListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700583 clusterService.removeListener(clusterListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700584
Charles Chan0aa674e2017-02-23 15:44:08 -0800585 neighbourResolutionService.unregisterNeighbourHandlers(appId);
586
sanghob35a6192015-04-01 13:05:26 -0700587 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700588 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700589 deviceListener = null;
Charles Chan6577f612018-04-19 13:10:01 -0700590 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chanb8e10c82015-10-14 11:24:40 -0700591 groupHandlerMap.clear();
Saurav Dasc6ff8f02018-04-23 18:42:12 -0700592 defaultRoutingHandler.shutdown();
Charles Chanb8e10c82015-10-14 11:24:40 -0700593
Saurav Das7bcbe702017-06-13 15:35:54 -0700594 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800595 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700596 portNextObjStore.destroy();
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700597 dummyVlanIdStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700598 tunnelStore.destroy();
599 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100600
601 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700602 log.info("Stopped");
603 }
604
Charles Chan47933752017-11-30 15:37:50 -0800605 @Modified
606 private void modified(ComponentContext context) {
607 Dictionary<?, ?> properties = context.getProperties();
608 if (properties == null) {
609 return;
610 }
611
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700612 String strActiveProbing = Tools.get(properties, "activeProbing");
613 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan47933752017-11-30 15:37:50 -0800614 if (expectActiveProbing != activeProbing) {
615 activeProbing = expectActiveProbing;
616 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
617 }
Saurav Das9a554292018-04-27 18:42:30 -0700618
619 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
620 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
621 if (expectSingleHomedDown != singleHomedDown) {
622 singleHomedDown = expectSingleHomedDown;
623 log.info("{} downing of single homed hosts for lost uplinks",
624 singleHomedDown ? "Enabling" : "Disabling");
625 if (singleHomedDown && linkHandler != null) {
626 hostService.getHosts().forEach(host -> host.locations()
627 .forEach(loc -> {
628 if (interfaceService.isConfigured(loc)) {
629 linkHandler.checkUplinksForHost(loc);
630 }
631 }));
632 } else {
633 log.warn("Disabling singleHomedDown does not re-enable already "
634 + "downed ports for single-homed hosts");
635 }
636 }
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700637
638 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
639 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
640 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
641 respondToUnknownHosts = expectRespondToUnknownHosts;
642 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
643 }
Charles Chan57465d32018-07-19 14:55:31 -0700644
Charles Chanb67dfdd2018-07-24 16:40:35 -0700645 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
646 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
647 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
648 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
649 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan57465d32018-07-19 14:55:31 -0700650
Charles Chanb67dfdd2018-07-24 16:40:35 -0700651 if (routeDoubleTaggedHosts) {
Charles Chan57465d32018-07-19 14:55:31 -0700652 hostHandler.populateAllDoubleTaggedHost();
653 } else {
654 hostHandler.revokeAllDoubleTaggedHost();
655 }
656 }
Saurav Das09c2c4d2018-08-13 15:34:26 -0700657
658 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
659 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
660 if (defIntVlan != defaultInternalVlan) {
661 if (canUseVlanId(defIntVlan)) {
662 log.warn("Default internal vlan value changed from {} to {}.. "
663 + "re-programming filtering rules, but NOT any groups already "
664 + "created with the former value", defaultInternalVlan, defIntVlan);
665 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
666 defaultInternalVlan = defIntVlan;
667 routingRulePopulator
668 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
669 VlanId.vlanId((short) defIntVlan));
670 } else {
671 log.warn("Cannot change default internal vlan to unusable "
672 + "value {}", defIntVlan);
673 }
674 }
675
676 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
677 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
678 if (pwTxpVlan != pwTransportVlan) {
679 if (canUseVlanId(pwTxpVlan)) {
680 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
681 + "re-programming filtering rules, but NOT any groups already "
682 + "created with the former value", pwTransportVlan,
683 pwTxpVlan);
684 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
685 pwTransportVlan = pwTxpVlan;
686 routingRulePopulator
687 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
688 VlanId.vlanId((short) pwTxpVlan));
689 } else {
690 log.warn("Cannot change pseudowire transport vlan to unusable "
691 + "value {}", pwTxpVlan);
692 }
693 }
694
695 }
696
697 /**
698 * Returns true if given vlan id is not being used in the system currently,
699 * either as one of the default system wide vlans or as one of the
700 * configured interface vlans.
701 *
702 * @param vlanId given vlan id
703 * @return true if vlan is not currently in use
704 */
705 public boolean canUseVlanId(int vlanId) {
706 if (vlanId >= 4095 || vlanId <= 1) {
707 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
708 vlanId);
709 return false;
710 }
711
712 VlanId vid = VlanId.vlanId((short) vlanId);
713 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
714 log.warn("Vlan id {} value is already in use system-wide. "
715 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
716 getDefaultInternalVlan(), getPwTransportVlan());
717 return false;
718 }
719
720 if (interfaceService.inUse(vid)) {
721 log.warn("Vlan id {} value is already in use on a configured "
722 + "interface in the system", vlanId);
723 return false;
724 }
725 return true;
726 }
727
728 /**
729 * Returns the VlanId assigned internally by default to unconfigured ports.
730 *
731 * @return the default internal vlan id
732 */
733 public VlanId getDefaultInternalVlan() {
734 return VlanId.vlanId((short) defaultInternalVlan);
735 }
736
737 /**
738 * Returns the Vlan id used to transport pseudowire traffic across the
739 * network.
740 *
741 * @return the pseudowire transport vlan id
742 */
743 public VlanId getPwTransportVlan() {
744 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan47933752017-11-30 15:37:50 -0800745 }
746
sangho1e575652015-05-14 00:39:53 -0700747 @Override
748 public List<Tunnel> getTunnels() {
749 return tunnelHandler.getTunnels();
750 }
751
752 @Override
sangho71abe1b2015-06-29 14:58:47 -0700753 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
754 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700755 }
756
757 @Override
sangho71abe1b2015-06-29 14:58:47 -0700758 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700759 for (Policy policy: policyHandler.getPolicies()) {
760 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
761 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
762 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
763 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700764 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700765 }
766 }
767 }
sangho71abe1b2015-06-29 14:58:47 -0700768 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700769 }
770
771 @Override
sangho71abe1b2015-06-29 14:58:47 -0700772 public PolicyHandler.Result removePolicy(Policy policy) {
773 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700774 }
775
776 @Override
sangho71abe1b2015-06-29 14:58:47 -0700777 public PolicyHandler.Result createPolicy(Policy policy) {
778 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700779 }
780
781 @Override
782 public List<Policy> getPolicies() {
783 return policyHandler.getPolicies();
784 }
785
Saurav Das59232cf2016-04-27 18:35:50 -0700786 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700787 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
788 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700789 }
790
791 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800792 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700793 return l2TunnelHandler.getL2Tunnels();
794 }
795
796 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800797 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700798 return l2TunnelHandler.getL2Policies();
799 }
800
Saurav Das5a356042018-04-06 20:16:01 -0700801 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700802 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700803 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
804
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700805 // get both added and pending pseudowires
806 List<L2TunnelDescription> pseudowires = new ArrayList<>();
807 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
808 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700809 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700810
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700811 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
812
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700813 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
814 L2TunnelHandler.Result res;
815 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
816 res = addPseudowire(pw);
817 if (res != L2TunnelHandler.Result.SUCCESS) {
818 log.error("Pseudowire with id {} can not be instantiated !", res);
819 retRes = res;
820 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700821 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700822
823 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700824 }
825
826 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800827 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700828 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700829 }
830
831 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800832 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700833 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700834 }
835
836 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700837 public void rerouteNetwork() {
838 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700839 }
840
Charles Chanc81c45b2016-10-20 17:02:44 -0700841 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800842 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
843 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800844 deviceConfiguration.getRouters().forEach(device ->
845 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700846 return deviceSubnetMap;
847 }
848
Saurav Dasc88d4662017-05-15 15:34:25 -0700849
850 @Override
851 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
852 if (defaultRoutingHandler != null) {
853 return defaultRoutingHandler.getCurrentEmcpSpgMap();
854 } else {
855 return null;
856 }
857 }
858
859 @Override
Charles Chand5814aa2018-08-19 19:21:46 -0700860 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das7bcbe702017-06-13 15:35:54 -0700861 if (dsNextObjStore != null) {
862 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700863 } else {
864 return ImmutableMap.of();
865 }
866 }
867
Saurav Dasceccf242017-08-03 18:30:35 -0700868 @Override
Charles Chand5814aa2018-08-19 19:21:46 -0700869 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
870 if (vlanNextObjStore != null) {
871 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
872 } else {
873 return ImmutableMap.of();
874 }
875 }
876
877 @Override
878 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
879 if (portNextObjStore != null) {
880 return ImmutableMap.copyOf(portNextObjStore.entrySet());
881 } else {
882 return ImmutableMap.of();
883 }
884 }
885
886 @Override
887 public ImmutableMap<String, NextObjective> getPwInitNext() {
888 if (l2TunnelHandler != null) {
889 return l2TunnelHandler.getInitNext();
890 } else {
891 return ImmutableMap.of();
892 }
893 }
894
895 @Override
896 public ImmutableMap<String, NextObjective> getPwTermNext() {
897 if (l2TunnelHandler != null) {
898 return l2TunnelHandler.getTermNext();
899 } else {
900 return ImmutableMap.of();
901 }
902 }
903
904 @Override
905 public void invalidateNextObj(int nextId) {
906 if (dsNextObjStore != null) {
907 dsNextObjStore.entrySet().forEach(e -> {
908 if (e.getValue().nextId() == nextId) {
909 dsNextObjStore.remove(e.getKey());
910 }
911 });
912 }
913 if (vlanNextObjStore != null) {
914 vlanNextObjStore.entrySet().forEach(e -> {
915 if (e.getValue() == nextId) {
916 vlanNextObjStore.remove(e.getKey());
917 }
918 });
919 }
920 if (portNextObjStore != null) {
921 portNextObjStore.entrySet().forEach(e -> {
922 if (e.getValue() == nextId) {
923 portNextObjStore.remove(e.getKey());
924 }
925 });
926 }
927 if (mcastHandler != null) {
928 mcastHandler.removeNextId(nextId);
929 }
930 if (l2TunnelHandler != null) {
931 l2TunnelHandler.removeNextId(nextId);
932 }
933 if (xconnectService != null) {
934 xconnectService.removeNextId(nextId);
935 }
936 }
937
938 @Override
Saurav Dasceccf242017-08-03 18:30:35 -0700939 public void verifyGroups(DeviceId id) {
940 DefaultGroupHandler gh = groupHandlerMap.get(id);
941 if (gh != null) {
942 gh.triggerBucketCorrector();
943 }
944 }
945
Saurav Dasc568c342018-01-25 09:49:01 -0800946 @Override
947 public ImmutableMap<Link, Boolean> getSeenLinks() {
948 return linkHandler.getSeenLinks();
949 }
950
951 @Override
952 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
953 return linkHandler.getDownedPorts();
954 }
955
Pier Luigib29144d2018-01-15 18:06:43 +0100956 @Override
957 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chand5814aa2018-08-19 19:21:46 -0700958 return mcastHandler.getNextIds(mcastIp);
Pier Luigib29144d2018-01-15 18:06:43 +0100959 }
960
961 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100962 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100963 return mcastHandler.getMcastRoles(mcastIp);
964 }
965
966 @Override
Pier3e793752018-04-19 16:47:06 +0200967 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
968 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
969 }
970
971 @Override
Pier Luigib29144d2018-01-15 18:06:43 +0100972 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
973 return mcastHandler.getMcastPaths(mcastIp);
974 }
975
Pier96f63cb2018-04-17 16:29:56 +0200976 @Override
Pierb1fe7382018-04-17 17:25:22 +0200977 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
978 ConnectPoint sourcecp) {
979 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
980 }
981
982 @Override
Pier96f63cb2018-04-17 16:29:56 +0200983 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
984 return mcastHandler.getMcastLeaders(mcastIp);
985 }
986
Charles Chan8bc75ee2018-04-17 18:56:53 -0700987 @Override
988 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
989 return defaultRoutingHandler == null ? ImmutableMap.of() :
990 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
991 }
992
993 @Override
994 public Map<DeviceId, Boolean> getShouldProgramCache() {
995 return defaultRoutingHandler == null ? ImmutableMap.of() :
996 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
997 }
998
Charles Chanc7b3c452018-06-19 20:31:57 -0700999 @Override
jayakumarthazhath655b9a82018-10-01 00:51:54 +05301000 public boolean shouldProgram(DeviceId deviceId) {
1001 return defaultRoutingHandler.shouldProgram(deviceId);
1002 }
1003
1004 @Override
Ray Milkeye4afdb52017-04-05 09:42:04 -07001005 public ApplicationId appId() {
1006 return appId;
1007 }
1008
1009 /**
1010 * Returns the device configuration.
1011 *
1012 * @return device configuration
1013 */
1014 public DeviceConfiguration deviceConfiguration() {
1015 return deviceConfiguration;
1016 }
1017
1018 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001019 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -07001020 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001021 *
1022 * @return next objective ID store
1023 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001024 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1025 dsNextObjStore() {
1026 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -07001027 }
1028
1029 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001030 * Per device next objective ID store with (device id + vlanid) as key.
1031 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001032 *
1033 * @return vlan next object store
1034 */
1035 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1036 return vlanNextObjStore;
1037 }
1038
1039 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001040 * Per device next objective ID store with (device id + port + treatment + meta) as key.
1041 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001042 *
1043 * @return port next object store.
1044 */
1045 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1046 return portNextObjStore;
1047 }
1048
1049 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001050 * Per port dummy VLAN ID store with (connect point + ip address) as key.
1051 * Used to keep track on dummy VLAN ID allocation.
1052 *
1053 * @return dummy vlan id store.
1054 */
1055 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
1056 return dummyVlanIdStore;
1057 }
1058
1059 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001060 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1061 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -07001062 *
1063 * @return MPLS-ECMP value
1064 */
1065 public boolean getMplsEcmp() {
1066 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1067 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1068 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1069 }
1070
1071 /**
sanghof9d0bf12015-05-19 11:57:42 -07001072 * Returns the tunnel object with the tunnel ID.
1073 *
1074 * @param tunnelId Tunnel ID
1075 * @return Tunnel reference
1076 */
sangho1e575652015-05-14 00:39:53 -07001077 public Tunnel getTunnel(String tunnelId) {
1078 return tunnelHandler.getTunnel(tunnelId);
1079 }
1080
Charles Chanc7b3c452018-06-19 20:31:57 -07001081 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +01001082 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan971d7ba2018-05-01 11:50:20 -07001083 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1084 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -07001085 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1086 }
1087
Charles Chanc7b3c452018-06-19 20:31:57 -07001088 @Override
1089 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001090 SegmentRoutingDeviceConfig deviceConfig =
1091 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1092 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1093 }
Charles Chanc7b3c452018-06-19 20:31:57 -07001094
1095 @Override
Saurav Das9a554292018-04-27 18:42:30 -07001096 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001097 SegmentRoutingDeviceConfig deviceConfig =
1098 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1099 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1100 }
1101
1102 /**
Charles Chan9640c812017-08-23 13:55:39 -07001103 * Returns locations of given resolved route.
1104 *
1105 * @param resolvedRoute resolved route
1106 * @return locations of nexthop. Might be empty if next hop is not found
1107 */
1108 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1109 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1110 return Optional.ofNullable(hostService.getHost(hostId))
1111 .map(Host::locations).orElse(Sets.newHashSet())
1112 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1113 }
1114
1115 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -08001116 * Returns vlan port map of given device.
1117 *
1118 * @param deviceId device id
1119 * @return vlan-port multimap
1120 */
1121 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1122 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1123
1124 interfaceService.getInterfaces().stream()
1125 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1126 .forEach(intf -> {
1127 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -07001128 intf.vlanTagged().forEach(vlanTagged ->
1129 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1130 );
Charles Chan7ffd81f2017-02-08 15:52:08 -08001131 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1132 });
1133 vlanPortMap.removeAll(VlanId.NONE);
1134
1135 return vlanPortMap;
1136 }
1137
1138 /**
Charles Chan59cc16d2017-02-02 16:20:42 -08001139 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -08001140 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -07001141 *
1142 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -08001143 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -08001144 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -07001145 */
Charles Chan65238242017-06-22 18:03:14 -07001146 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -07001147 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -08001148 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1149 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001150 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -08001151 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -08001152 + "device {} not found", deviceId);
1153 return -1;
1154 }
1155 }
1156
1157 /**
1158 * Returns the next objective ID for the given portNumber, given the treatment.
1159 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -07001160 * would result in different objectives. If the next object does not exist,
1161 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -08001162 *
1163 * @param deviceId Device ID
1164 * @param portNum port number on device for which NextObjective is queried
1165 * @param treatment the actions to apply on the packets (should include outport)
1166 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -07001167 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -07001168 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -08001169 */
1170 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1171 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -07001172 TrafficSelector meta,
1173 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -08001174 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1175 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -07001176 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -08001177 } else {
Charles Chane849c192016-01-11 18:28:54 -08001178 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1179 + " not found", deviceId);
1180 return -1;
1181 }
1182 }
1183
Saurav Dasc88d4662017-05-15 15:34:25 -07001184 /**
1185 * Returns the group handler object for the specified device id.
1186 *
1187 * @param devId the device identifier
1188 * @return the groupHandler object for the device id, or null if not found
1189 */
Charles Chan65238242017-06-22 18:03:14 -07001190 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001191 return groupHandlerMap.get(devId);
1192 }
1193
1194 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001195 * Returns the default routing handler object.
1196 *
1197 * @return the default routing handler object
1198 */
1199 public DefaultRoutingHandler getRoutingHandler() {
1200 return defaultRoutingHandler;
1201 }
1202
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001203 /**
1204 * Returns new dummy VLAN ID.
1205 * Dummy VLAN ID should be unique in each connect point.
1206 *
1207 * @param cp connect point
1208 * @param ipAddress IP address
1209 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1210 */
1211 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1212 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1213 dummyVlanIdStore.entrySet().stream().filter(entry ->
1214 (entry.getKey()).connectPoint().equals(cp))
1215 .map(Map.Entry::getValue)
1216 .collect(Collectors.toSet()));
1217
1218 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1219 i -> VlanId.vlanId((short) (i & 0xFFFF))
1220 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1221
1222 if (!dummyVlanId.equals(VlanId.NONE)) {
1223 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1224 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1225 } else {
1226 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1227 }
1228 return dummyVlanId;
1229 }
1230
1231
sanghob35a6192015-04-01 13:05:26 -07001232 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001233 @Override
1234 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -07001235 packetExecutor.execute(() -> processPacketInternal(context));
1236 }
sanghob35a6192015-04-01 13:05:26 -07001237
Charles Chan07f15f22018-05-08 21:35:50 -07001238 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001239 if (context.isHandled()) {
1240 return;
1241 }
1242
1243 InboundPacket pkt = context.inPacket();
1244 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001245
1246 if (ethernet == null) {
1247 return;
1248 }
1249
Saurav Das7bcbe702017-06-13 15:35:54 -07001250 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1251 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001252 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001253 log.warn("Received unexpected ARP packet on {}",
1254 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001255 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001256 return;
sanghob35a6192015-04-01 13:05:26 -07001257 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001258 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1259 //ipHandler.addToPacketBuffer(ipv4Packet);
1260 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1261 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001262 } else {
Charles Chan50035632017-01-13 17:20:44 -08001263 // NOTE: We don't support IP learning at this moment so this
1264 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001265 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001266 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001267 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1268 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001269 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001270 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001271 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1272 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1273 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1274 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1275 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1276 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001277 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001278 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001279 }
1280 } else {
1281 // NOTE: We don't support IP learning at this moment so this
1282 // is not necessary. Also it causes duplication of DHCPv6 packets.
1283 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1284 }
sanghob35a6192015-04-01 13:05:26 -07001285 }
1286 }
1287 }
1288
sanghob35a6192015-04-01 13:05:26 -07001289 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001290 private Event event;
1291
1292 InternalEventHandler(Event event) {
1293 this.event = event;
1294 }
1295
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001296 @Override
sanghob35a6192015-04-01 13:05:26 -07001297 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001298 try {
1299 // TODO We should also change SR routing and PW to listen to TopologyEvents
1300 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1301 event.type() == LinkEvent.Type.LINK_UPDATED) {
1302 linkHandler.processLinkAdded((Link) event.subject());
1303 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1304 linkHandler.processLinkRemoved((Link) event.subject());
1305 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1306 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1307 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1308 DeviceId deviceId = ((Device) event.subject()).id();
1309 if (deviceService.isAvailable(deviceId)) {
1310 log.info("** DEVICE UP Processing device event {} "
1311 + "for available device {}",
1312 event.type(), ((Device) event.subject()).id());
1313 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001314 } else {
Charles Chan7040b692018-08-29 21:21:51 -07001315 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1316 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1317 // The device will later on being marked as available once the pipeline is pushed
1318 // to the device.
1319 log.info("** DEVICE ADDED but unavailable. Ignore");
1320 return;
1321 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001322 log.info(" ** DEVICE DOWN Processing device event {}"
1323 + " for unavailable device {}",
1324 event.type(), ((Device) event.subject()).id());
1325 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001326 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001327 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1328 // typically these calls come when device is added first time
1329 // so port filtering rules are handled at the device_added event.
1330 // port added calls represent all ports on the device,
1331 // enabled or not.
1332 log.trace("** PORT ADDED {}/{} -> {}",
1333 ((DeviceEvent) event).subject().id(),
1334 ((DeviceEvent) event).port().number(),
1335 event.type());
1336 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1337 // these calls happen for every subsequent event
1338 // ports enabled, disabled, switch goes away, comes back
1339 log.info("** PORT UPDATED {}/{} -> {}",
1340 event.subject(),
1341 ((DeviceEvent) event).port(),
1342 event.type());
Saurav Das9a554292018-04-27 18:42:30 -07001343 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001344 ((DeviceEvent) event).port());
1345 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1346 // Process topology event, needed for all modules relying on
1347 // topology service for path computation
1348 TopologyEvent topologyEvent = (TopologyEvent) event;
1349 log.info("Processing topology event {}, topology age {}, reasons {}",
1350 event.type(), topologyEvent.subject().time(),
1351 topologyEvent.reasons().size());
1352 topologyHandler.processTopologyChange(topologyEvent.reasons());
1353 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1354 hostHandler.processHostAddedEvent((HostEvent) event);
1355 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1356 hostHandler.processHostMovedEvent((HostEvent) event);
1357 routeHandler.processHostMovedEvent((HostEvent) event);
1358 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1359 hostHandler.processHostRemovedEvent((HostEvent) event);
1360 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1361 hostHandler.processHostUpdatedEvent((HostEvent) event);
1362 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1363 routeHandler.processRouteAdded((RouteEvent) event);
1364 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1365 routeHandler.processRouteUpdated((RouteEvent) event);
1366 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1367 routeHandler.processRouteRemoved((RouteEvent) event);
1368 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1369 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1370 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1371 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1372 event.type() == McastEvent.Type.SINKS_ADDED ||
1373 event.type() == McastEvent.Type.SINKS_REMOVED ||
1374 event.type() == McastEvent.Type.ROUTE_ADDED ||
1375 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1376 mcastHandler.processMcastEvent((McastEvent) event);
1377 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1378 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1379 Class configClass = netcfgEvent.configClass();
1380 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1381 appCfgHandler.processAppConfigAdded(netcfgEvent);
1382 log.info("App config event .. configuring network");
1383 cfgListener.configureNetwork();
1384 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1385 log.info("Segment Routing Device Config added for {}", event.subject());
1386 cfgListener.configureNetwork();
1387 } else if (configClass.equals(XConnectConfig.class)) {
1388 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1389 } else if (configClass.equals(InterfaceConfig.class)) {
1390 log.info("Interface Config added for {}", event.subject());
1391 cfgListener.configureNetwork();
1392 } else {
1393 log.error("Unhandled config class: {}", configClass);
1394 }
1395 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1396 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1397 Class configClass = netcfgEvent.configClass();
1398 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1399 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1400 log.info("App config event .. configuring network");
1401 cfgListener.configureNetwork();
1402 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1403 log.info("Segment Routing Device Config updated for {}", event.subject());
1404 createOrUpdateDeviceConfiguration();
1405 } else if (configClass.equals(XConnectConfig.class)) {
1406 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1407 } else if (configClass.equals(InterfaceConfig.class)) {
1408 log.info("Interface Config updated for {}", event.subject());
1409 createOrUpdateDeviceConfiguration();
1410 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1411 (InterfaceConfig) netcfgEvent.prevConfig().get());
1412 } else {
1413 log.error("Unhandled config class: {}", configClass);
1414 }
1415 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1416 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1417 Class configClass = netcfgEvent.configClass();
1418 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1419 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1420 log.info("App config event .. configuring network");
1421 cfgListener.configureNetwork();
1422 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1423 // TODO Handle sr device config removal
1424 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1425 } else if (configClass.equals(XConnectConfig.class)) {
1426 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1427 } else if (configClass.equals(InterfaceConfig.class)) {
1428 // TODO Handle interface removal
1429 log.info("InterfaceConfig removal is not handled in current implementation");
1430 } else {
1431 log.error("Unhandled config class: {}", configClass);
1432 }
Saurav Das201762d2018-04-21 17:19:48 -07001433 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1434 MastershipEvent me = (MastershipEvent) event;
1435 DeviceId deviceId = me.subject();
1436 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1437 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1438 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1439 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1440 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1441 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001442 } else {
1443 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001444 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001445 } catch (Exception e) {
1446 log.error("SegmentRouting event handler thread thrown an exception: {}",
1447 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001448 }
sanghob35a6192015-04-01 13:05:26 -07001449 }
1450 }
1451
Saurav Das45f48152018-01-18 12:07:33 -08001452 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001453 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001454
1455 // NOTE: Punt ARP/NDP even when the device is not configured.
1456 // Host learning without network config is required for CORD config generator.
1457 routingRulePopulator.populateIpPunts(device.id());
1458 routingRulePopulator.populateArpNdpPunts(device.id());
1459
Charles Chan0b4e6182015-11-03 10:42:14 -08001460 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001461 log.warn("Device configuration unavailable. Device {} will be "
1462 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001463 return;
1464 }
Charles Chan2199c302016-04-23 17:36:10 -07001465 processDeviceAddedInternal(device.id());
1466 }
1467
1468 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001469 // Irrespective of whether the local is a MASTER or not for this device,
1470 // we need to create a SR-group-handler instance. This is because in a
1471 // multi-instance setup, any instance can initiate forwarding/next-objectives
1472 // for any switch (even if this instance is a SLAVE or not even connected
1473 // to the switch). To handle this, a default-group-handler instance is necessary
1474 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001475 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1476 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001477 DefaultGroupHandler groupHandler;
1478 try {
1479 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001480 createGroupHandler(deviceId,
1481 appId,
1482 deviceConfiguration,
1483 linkService,
1484 flowObjectiveService,
1485 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001486 } catch (DeviceConfigNotFoundException e) {
1487 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1488 return;
1489 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001490 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001491 deviceId);
1492 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001493 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001494
Charles Chan2199c302016-04-23 17:36:10 -07001495 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001496 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001497 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001498 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001499 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001500 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001501 }
Charles Chan5270ed02016-01-30 23:22:37 -08001502
Charles Chan03a73e02016-10-24 14:52:01 -07001503 appCfgHandler.init(deviceId);
Charles Chan94549652018-04-29 18:11:37 -07001504 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1505 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001506 }
1507
Saurav Das80980c72016-03-23 11:22:49 -07001508 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001509 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001510 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001511 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001512 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001513 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001514 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001515 portNextObjStore.entrySet().stream()
1516 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001517 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001518 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001519
Saurav Dasceccf242017-08-03 18:30:35 -07001520 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1521 if (gh != null) {
1522 gh.shutdown();
1523 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001524 // Note that a switch going down is associated with all of its links
1525 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001526 // while the link-downs are ignored. We cannot rely on the ordering of
1527 // events - i.e we cannot expect all link-downs to come before the
1528 // switch down - so we purge all seen-links for the switch before
1529 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001530 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001531 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001532 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001533 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001534
1535 // Cleanup all internal groupHandler stores for this device. Should be
1536 // done after all rerouting or rehashing has been completed
1537 groupHandlerMap.entrySet()
1538 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001539 }
1540
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001541 /**
1542 * Purge the destinationSet nextObjective store of entries with this device
1543 * as key. Erases app-level knowledge of hashed groups in this device.
1544 *
1545 * @param devId the device identifier
1546 */
Saurav Das201762d2018-04-21 17:19:48 -07001547 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001548 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das201762d2018-04-21 17:19:48 -07001549 dsNextObjStore.entrySet().stream()
1550 .filter(entry -> entry.getKey().deviceId().equals(devId))
1551 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1552 }
1553
Saurav Das9a554292018-04-27 18:42:30 -07001554 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001555 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1556 log.warn("Device configuration uploading. Not handling port event for"
1557 + "dev: {} port: {}", device.id(), port.number());
1558 return;
1559 }
Saurav Das018605f2017-02-18 14:05:44 -08001560
Saurav Das9a554292018-04-27 18:42:30 -07001561 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1562 lastEdgePortEvent = Instant.now();
1563 }
1564
Saurav Das018605f2017-02-18 14:05:44 -08001565 if (!mastershipService.isLocalMaster(device.id())) {
1566 log.debug("Not master for dev:{} .. not handling port updated event"
1567 + "for port {}", device.id(), port.number());
1568 return;
1569 }
Saurav Das9a554292018-04-27 18:42:30 -07001570 processPortUpdated(device.id(), port);
1571 }
Saurav Das018605f2017-02-18 14:05:44 -08001572
Saurav Das9a554292018-04-27 18:42:30 -07001573 /**
1574 * Adds or remove filtering rules for the given switchport. If switchport is
1575 * an edge facing port, additionally handles host probing and broadcast
1576 * rules. Must be called by local master of device.
1577 *
1578 * @param deviceId the device identifier
1579 * @param port the port to update
1580 */
1581 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001582 // first we handle filtering rules associated with the port
1583 if (port.isEnabled()) {
1584 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das9a554292018-04-27 18:42:30 -07001585 deviceId, port.number());
1586 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001587 } else {
1588 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das9a554292018-04-27 18:42:30 -07001589 deviceId, port.number());
1590 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001591 }
Saurav Das1a129a02016-11-18 15:21:57 -08001592
1593 // portUpdated calls are for ports that have gone down or up. For switch
1594 // to switch ports, link-events should take care of any re-routing or
1595 // group editing necessary for port up/down. Here we only process edge ports
1596 // that are already configured.
Saurav Das9a554292018-04-27 18:42:30 -07001597 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan971d7ba2018-05-01 11:50:20 -07001598 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1599 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1600 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001601
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001602 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001603 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das9a554292018-04-27 18:42:30 -07001604 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001605 return;
1606 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001607 if (untaggedVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001608 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001609 }
1610 if (nativeVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001611 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001612 }
1613 if (!taggedVlans.isEmpty()) {
Saurav Das9a554292018-04-27 18:42:30 -07001614 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001615 }
Saurav Das1a129a02016-11-18 15:21:57 -08001616 }
1617
Saurav Das9a554292018-04-27 18:42:30 -07001618 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001619 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001620 boolean portUp = port.isEnabled();
1621 if (portUp) {
Saurav Das9a554292018-04-27 18:42:30 -07001622 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001623 port.number(), vlanId);
Charles Chan94549652018-04-29 18:11:37 -07001624 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001625 } else {
Saurav Das9a554292018-04-27 18:42:30 -07001626 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001627 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001628 }
1629
Saurav Das9a554292018-04-27 18:42:30 -07001630 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001631 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001632 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001633 } else {
1634 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das9a554292018-04-27 18:42:30 -07001635 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001636 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001637 }
1638 }
sangho1e575652015-05-14 00:39:53 -07001639
Charles Chan27fe1a52017-10-20 16:06:55 -07001640 private void createOrUpdateDeviceConfiguration() {
1641 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001642 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001643 deviceConfiguration = new DeviceConfiguration(this);
1644 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001645 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001646 deviceConfiguration.updateConfig();
1647 }
1648 }
1649
Charles Chan50bb6ef2018-04-18 18:41:05 -07001650 private void createOrUpdateDefaultRoutingHandler() {
1651 if (defaultRoutingHandler == null) {
1652 log.info("Creating new DefaultRoutingHandler");
1653 defaultRoutingHandler = new DefaultRoutingHandler(this);
1654 } else {
1655 log.info("Updating DefaultRoutingHandler");
1656 defaultRoutingHandler.update(this);
1657 }
1658 }
1659
Pier Ventre10bd8d12016-11-26 21:05:22 -08001660 /**
1661 * Registers the given connect point with the NRS, this is necessary
1662 * to receive the NDP and ARP packets from the NRS.
1663 *
1664 * @param portToRegister connect point to register
1665 */
1666 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001667 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001668 portToRegister,
1669 neighbourHandler,
1670 appId
1671 );
1672 }
1673
Charles Chand6832882015-10-05 17:50:33 -07001674 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001675 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001676 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001677
Charles Chane849c192016-01-11 18:28:54 -08001678 /**
1679 * Constructs the internal network config listener.
1680 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001681 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001682 */
Charles Chan65238242017-06-22 18:03:14 -07001683 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001684 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001685 }
1686
Charles Chane849c192016-01-11 18:28:54 -08001687 /**
1688 * Reads network config and initializes related data structure accordingly.
1689 */
Charles Chan47933752017-11-30 15:37:50 -08001690 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001691 log.info("Configuring network ...");
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001692
1693 // Setting handling of network configuration events completable future
1694 // The completable future is needed because of the async behaviour of the configureNetwork,
1695 // listener registration and event arrival
1696 // Enables us to buffer the events and execute them when the configure network is done.
1697 networkConfigCompletion = new CompletableFuture<>();
1698
1699 // add a small delay to absorb multiple network config added notifications
1700 if (!programmingScheduled.get()) {
1701 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1702 programmingScheduled.set(true);
1703 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1704 }
1705
Charles Chan27fe1a52017-10-20 16:06:55 -07001706 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001707
Charles Chan2c15aca2016-11-09 20:51:44 -08001708 arpHandler = new ArpHandler(srManager);
1709 icmpHandler = new IcmpHandler(srManager);
1710 ipHandler = new IpHandler(srManager);
1711 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chan50bb6ef2018-04-18 18:41:05 -07001712 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001713
1714 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1715 groupHandlerMap, tunnelStore);
1716 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1717 flowObjectiveService,
1718 tunnelHandler, policyStore);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001719 networkConfigCompletion.complete(true);
1720
Charles Chan2199c302016-04-23 17:36:10 -07001721 mcastHandler.init();
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001722
Charles Chan4636be02015-10-07 14:21:45 -07001723 }
1724
Charles Chand6832882015-10-05 17:50:33 -07001725 @Override
1726 public void event(NetworkConfigEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001727 if (mainEventExecutor == null) {
1728 return;
1729 }
Charles Chan7a888e82018-03-21 16:57:47 -07001730 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1731 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1732 switch (event.type()) {
1733 case CONFIG_ADDED:
1734 case CONFIG_UPDATED:
1735 case CONFIG_REMOVED:
1736 log.trace("Schedule Network Config event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001737 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1738 mainEventExecutor.execute(new InternalEventHandler(event));
1739 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001740 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001741 }
Charles Chan7a888e82018-03-21 16:57:47 -07001742 break;
1743 default:
1744 break;
Charles Chand6832882015-10-05 17:50:33 -07001745 }
1746 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001747
Charles Chan50443e82018-01-03 16:26:32 -08001748 @Override
1749 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001750 if (event.type() == CONFIG_REGISTERED ||
1751 event.type() == CONFIG_UNREGISTERED) {
1752 log.debug("Ignore event {} due to type mismatch", event);
1753 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001754 }
Saurav Dase7f51012018-02-09 17:26:45 -08001755
1756 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1757 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1758 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001759 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001760 log.debug("Ignore event {} due to class mismatch", event);
1761 return false;
1762 }
1763
1764 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001765 }
1766
Saurav Das7bcbe702017-06-13 15:35:54 -07001767 private final class ConfigChange implements Runnable {
1768 @Override
1769 public void run() {
1770 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001771 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001772 for (Device device : deviceService.getDevices()) {
1773 processDeviceAdded(device);
1774 }
1775 defaultRoutingHandler.startPopulationProcess();
1776 }
1777 }
Charles Chand6832882015-10-05 17:50:33 -07001778 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001779
Charles Chan7a888e82018-03-21 16:57:47 -07001780 private class InternalLinkListener implements LinkListener {
1781 @Override
1782 public void event(LinkEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001783 if (mainEventExecutor == null) {
1784 return;
1785 }
Charles Chan7a888e82018-03-21 16:57:47 -07001786 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1787 event.type() == LinkEvent.Type.LINK_UPDATED ||
1788 event.type() == LinkEvent.Type.LINK_REMOVED) {
1789 log.trace("Schedule Link event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001790 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1791 mainEventExecutor.execute(new InternalEventHandler(event));
1792 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001793 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001794 }
Charles Chan7a888e82018-03-21 16:57:47 -07001795 }
1796 }
1797 }
1798
1799 private class InternalDeviceListener implements DeviceListener {
1800 @Override
1801 public void event(DeviceEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001802 if (mainEventExecutor == null) {
1803 return;
1804 }
Charles Chan7a888e82018-03-21 16:57:47 -07001805 switch (event.type()) {
1806 case DEVICE_ADDED:
1807 case PORT_UPDATED:
1808 case PORT_ADDED:
1809 case DEVICE_UPDATED:
1810 case DEVICE_AVAILABILITY_CHANGED:
1811 log.trace("Schedule Device event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001812 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1813 mainEventExecutor.execute(new InternalEventHandler(event));
1814 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001815 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001816 }
Charles Chan7a888e82018-03-21 16:57:47 -07001817 break;
1818 default:
1819 }
1820 }
1821 }
1822
1823 private class InternalTopologyListener implements TopologyListener {
1824 @Override
1825 public void event(TopologyEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001826 if (mainEventExecutor == null) {
1827 return;
1828 }
Charles Chan7a888e82018-03-21 16:57:47 -07001829 switch (event.type()) {
1830 case TOPOLOGY_CHANGED:
1831 log.trace("Schedule Topology event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001832 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1833 mainEventExecutor.execute(new InternalEventHandler(event));
1834 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001835 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001836 }
Charles Chan7a888e82018-03-21 16:57:47 -07001837 break;
1838 default:
1839 }
1840 }
1841 }
1842
Charles Chan68aa62d2015-11-09 16:37:23 -08001843 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001844 @Override
1845 public void event(HostEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001846 if (hostEventExecutor == null) {
1847 return;
1848 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001849 switch (event.type()) {
1850 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001851 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001852 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001853 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001854 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001855 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001856 break;
1857 default:
1858 log.warn("Unsupported host event type: {}", event.type());
1859 break;
1860 }
1861 }
1862 }
1863
Charles Chand55e84d2016-03-30 17:54:24 -07001864 private class InternalMcastListener implements McastListener {
1865 @Override
1866 public void event(McastEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001867 if (mcastEventExecutor == null) {
1868 return;
1869 }
Charles Chand55e84d2016-03-30 17:54:24 -07001870 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001871 case SOURCES_ADDED:
1872 case SOURCES_REMOVED:
1873 case SINKS_ADDED:
1874 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001875 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001876 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001877 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001878 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001879 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001880 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001881 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001882 break;
1883 }
1884 }
1885 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001886
Charles Chan03a73e02016-10-24 14:52:01 -07001887 private class InternalRouteEventListener implements RouteListener {
1888 @Override
1889 public void event(RouteEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001890 if (routeEventExecutor == null) {
1891 return;
1892 }
Charles Chan03a73e02016-10-24 14:52:01 -07001893 switch (event.type()) {
1894 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001895 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001896 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001897 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001898 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001899 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001900 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001901 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001902 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001903 break;
1904 }
1905 }
1906 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001907
Charles Chan50bb6ef2018-04-18 18:41:05 -07001908 private class InternalMastershipListener implements MastershipListener {
1909 @Override
1910 public void event(MastershipEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001911 if (mainEventExecutor == null) {
1912 return;
1913 }
Charles Chan50bb6ef2018-04-18 18:41:05 -07001914 switch (event.type()) {
Saurav Das201762d2018-04-21 17:19:48 -07001915 case MASTER_CHANGED:
1916 log.debug("Mastership event: {}/{}", event.subject(),
1917 event.roleInfo());
1918 mainEventExecutor.execute(new InternalEventHandler(event));
1919 break;
1920 case BACKUPS_CHANGED:
1921 case SUSPENDED:
1922 default:
1923 log.debug("Mastership event type {} not handled", event.type());
1924 break;
Charles Chan50bb6ef2018-04-18 18:41:05 -07001925 }
1926 }
1927 }
1928
Saurav Das201762d2018-04-21 17:19:48 -07001929 class InternalClusterListener implements ClusterEventListener {
1930 private Instant lastClusterEvent = Instant.EPOCH;
1931
1932 long timeSinceLastClusterEvent() {
1933 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1934 }
1935
1936 @Override
1937 public void event(ClusterEvent event) {
1938 switch (event.type()) {
1939 case INSTANCE_ACTIVATED:
1940 case INSTANCE_ADDED:
1941 case INSTANCE_READY:
1942 log.debug("Cluster event {} ignored", event.type());
1943 break;
1944 case INSTANCE_DEACTIVATED:
1945 case INSTANCE_REMOVED:
1946 log.info("** Cluster event {}", event.type());
1947 lastClusterEvent = Instant.now();
1948 break;
1949 default:
1950 break;
1951 }
1952
1953 }
1954
1955 }
1956
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001957 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1958 try {
1959 Set<Interface> intfs = conf.getInterfaces();
1960 Set<Interface> prevIntfs = prevConf.getInterfaces();
1961
1962 // Now we only handle one interface config at each port.
1963 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1964 log.warn("Interface update aborted - one at a time is allowed, " +
1965 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1966 return;
1967 }
1968
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001969 //The system is in an incoherent state, abort
1970 if (defaultRoutingHandler == null) {
1971 log.warn("Interface update aborted, defaultRoutingHandler is null");
1972 return;
1973 }
1974
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001975 Interface intf = intfs.stream().findFirst().get();
1976 Interface prevIntf = prevIntfs.stream().findFirst().get();
1977
1978 DeviceId deviceId = intf.connectPoint().deviceId();
1979 PortNumber portNum = intf.connectPoint().port();
1980
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001981 removeSubnetConfig(prevIntf.connectPoint(),
1982 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1983 new HashSet<>(intf.ipAddressesList())));
1984
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001985 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1986 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1987 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1988 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1989 // Update filtering objective and L2IG group bucket
1990 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1991 } else {
1992 // RemoveVlanNative
1993 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1994 }
1995 }
1996
1997 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1998 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1999 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2000 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
2001 // Update filtering objective and L2IG group bucket
2002 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
2003 } else {
2004 // RemoveVlanUntagged
2005 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
2006 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002007 }
2008
2009 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2010 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002011 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2012 .filter(i -> !intf.vlanUntagged().equals(i))
2013 .filter(i -> !intf.vlanNative().equals(i))
2014 .forEach(vlanId -> updateVlanConfigInternal(
2015 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002016 }
2017
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002018 if (!intf.vlanNative().equals(VlanId.NONE)
2019 && !prevIntf.vlanNative().equals(intf.vlanNative())
2020 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2021 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2022 // Update filtering objective and L2IG group bucket
2023 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2024 } else {
2025 // AddVlanNative
2026 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2027 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002028 }
2029
2030 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2031 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002032 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2033 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2034 .filter(i -> !prevIntf.vlanNative().equals(i))
2035 .forEach(vlanId -> updateVlanConfigInternal(
2036 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002037 );
2038 }
2039
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002040 if (!intf.vlanUntagged().equals(VlanId.NONE)
2041 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2042 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2043 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2044 // Update filtering objective and L2IG group bucket
2045 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2046 } else {
2047 // AddVlanUntagged
2048 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2049 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002050 }
2051 addSubnetConfig(prevIntf.connectPoint(),
2052 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2053 new HashSet<>(prevIntf.ipAddressesList())));
2054 } catch (ConfigException e) {
2055 log.error("Error in configuration");
2056 }
2057 }
2058
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002059 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2060 VlanId vlanId, boolean pushVlan) {
2061 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2062 if (grpHandler == null) {
2063 log.warn("Failed to retrieve group handler for device {}", deviceId);
2064 return;
2065 }
2066
2067 // Update filtering objective for a single port
2068 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2069 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2070
2071 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2072 // Update L2IG bucket of the port
2073 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2074 } else {
2075 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2076 }
2077 }
2078
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002079 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2080 VlanId vlanId, boolean pushVlan, boolean install) {
2081 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2082 if (grpHandler == null) {
2083 log.warn("Failed to retrieve group handler for device {}", deviceId);
2084 return;
2085 }
2086
2087 // Update filtering objective for a single port
2088 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2089
2090 // Update filtering objective for multicast ingress port
2091 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2092
2093 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2094
2095 if (nextId != -1 && !install) {
2096 // Update next objective for a single port as an output port
2097 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002098 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002099 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan94549652018-04-29 18:11:37 -07002100 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2101 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002102 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2103 // only if there is no port configured on that VLAN ID
2104 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2105 // Remove broadcast forwarding rule for the VLAN
2106 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2107 // Remove L2FG for VLAN
2108 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2109 } else {
2110 // Remove L2IG of the port
2111 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2112 }
2113 } else if (install) {
2114 if (nextId != -1) {
2115 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002116 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002117 } else {
2118 // Create L2FG for VLAN
2119 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2120 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2121 }
Charles Chan94549652018-04-29 18:11:37 -07002122 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2123 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002124 } else {
2125 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2126 }
2127 }
2128
2129 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2130 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2131 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2132
2133 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2134 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2135 .filter(intf -> !intf.connectPoint().equals(cp))
2136 .flatMap(intf -> intf.ipAddressesList().stream())
2137 .collect(Collectors.toSet());
2138 // 1. Partial subnet population
2139 // Remove routing rules for removed subnet from previous configuration,
2140 // which does not also exist in other interfaces in the same device
2141 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2142 .map(InterfaceIpAddress::subnetAddress)
2143 .collect(Collectors.toSet());
2144
2145 defaultRoutingHandler.revokeSubnet(
2146 ipPrefixSet.stream()
2147 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2148 .collect(Collectors.toSet()));
2149
2150 // 2. Interface IP punts
2151 // Remove IP punts for old Intf address
2152 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2153 .map(InterfaceIpAddress::ipAddress)
2154 .collect(Collectors.toSet());
2155 ipAddressSet.stream()
2156 .map(InterfaceIpAddress::ipAddress)
2157 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2158 .forEach(interfaceIpAddress ->
2159 routingRulePopulator.revokeSingleIpPunts(
2160 cp.deviceId(), interfaceIpAddress));
2161
2162 // 3. Host unicast routing rule
2163 // Remove unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002164 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002165 }
2166
2167 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2168 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2169 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2170
2171 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2172 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2173 .filter(intf -> !intf.connectPoint().equals(cp))
2174 .flatMap(intf -> intf.ipAddressesList().stream())
2175 .collect(Collectors.toSet());
2176 // 1. Partial subnet population
2177 // Add routing rules for newly added subnet, which does not also exist in
2178 // other interfaces in the same device
2179 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2180 .map(InterfaceIpAddress::subnetAddress)
2181 .collect(Collectors.toSet());
2182
2183 defaultRoutingHandler.populateSubnet(
2184 Collections.singleton(cp),
2185 ipPrefixSet.stream()
2186 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2187 .collect(Collectors.toSet()));
2188
2189 // 2. Interface IP punts
2190 // Add IP punts for new Intf address
2191 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2192 .map(InterfaceIpAddress::ipAddress)
2193 .collect(Collectors.toSet());
2194 ipAddressSet.stream()
2195 .map(InterfaceIpAddress::ipAddress)
2196 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2197 .forEach(interfaceIpAddress ->
2198 routingRulePopulator.populateSingleIpPunts(
2199 cp.deviceId(), interfaceIpAddress));
2200
2201 // 3. Host unicast routing rule
2202 // Add unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002203 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002204 }
sanghob35a6192015-04-01 13:05:26 -07002205}