blob: 19b03043757a2bfd6998907ff981981d350a9777 [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",
478 "fallbackFlowPollFrequency", "5");
479 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
480 "fallbackGroupPollFrequency", "5");
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
Ray Milkeye4afdb52017-04-05 09:42:04 -07001000 public ApplicationId appId() {
1001 return appId;
1002 }
1003
1004 /**
1005 * Returns the device configuration.
1006 *
1007 * @return device configuration
1008 */
1009 public DeviceConfiguration deviceConfiguration() {
1010 return deviceConfiguration;
1011 }
1012
1013 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001014 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -07001015 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001016 *
1017 * @return next objective ID store
1018 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001019 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1020 dsNextObjStore() {
1021 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -07001022 }
1023
1024 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001025 * Per device next objective ID store with (device id + vlanid) as key.
1026 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001027 *
1028 * @return vlan next object store
1029 */
1030 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1031 return vlanNextObjStore;
1032 }
1033
1034 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001035 * Per device next objective ID store with (device id + port + treatment + meta) as key.
1036 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001037 *
1038 * @return port next object store.
1039 */
1040 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1041 return portNextObjStore;
1042 }
1043
1044 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001045 * Per port dummy VLAN ID store with (connect point + ip address) as key.
1046 * Used to keep track on dummy VLAN ID allocation.
1047 *
1048 * @return dummy vlan id store.
1049 */
1050 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
1051 return dummyVlanIdStore;
1052 }
1053
1054 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001055 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1056 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -07001057 *
1058 * @return MPLS-ECMP value
1059 */
1060 public boolean getMplsEcmp() {
1061 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1062 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1063 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1064 }
1065
1066 /**
sanghof9d0bf12015-05-19 11:57:42 -07001067 * Returns the tunnel object with the tunnel ID.
1068 *
1069 * @param tunnelId Tunnel ID
1070 * @return Tunnel reference
1071 */
sangho1e575652015-05-14 00:39:53 -07001072 public Tunnel getTunnel(String tunnelId) {
1073 return tunnelHandler.getTunnel(tunnelId);
1074 }
1075
Charles Chanc7b3c452018-06-19 20:31:57 -07001076 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +01001077 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan971d7ba2018-05-01 11:50:20 -07001078 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1079 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -07001080 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1081 }
1082
Charles Chanc7b3c452018-06-19 20:31:57 -07001083 @Override
1084 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001085 SegmentRoutingDeviceConfig deviceConfig =
1086 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1087 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1088 }
Charles Chanc7b3c452018-06-19 20:31:57 -07001089
1090 @Override
Saurav Das9a554292018-04-27 18:42:30 -07001091 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001092 SegmentRoutingDeviceConfig deviceConfig =
1093 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1094 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1095 }
1096
1097 /**
Charles Chan9640c812017-08-23 13:55:39 -07001098 * Returns locations of given resolved route.
1099 *
1100 * @param resolvedRoute resolved route
1101 * @return locations of nexthop. Might be empty if next hop is not found
1102 */
1103 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1104 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1105 return Optional.ofNullable(hostService.getHost(hostId))
1106 .map(Host::locations).orElse(Sets.newHashSet())
1107 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1108 }
1109
1110 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -08001111 * Returns vlan port map of given device.
1112 *
1113 * @param deviceId device id
1114 * @return vlan-port multimap
1115 */
1116 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1117 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1118
1119 interfaceService.getInterfaces().stream()
1120 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1121 .forEach(intf -> {
1122 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -07001123 intf.vlanTagged().forEach(vlanTagged ->
1124 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1125 );
Charles Chan7ffd81f2017-02-08 15:52:08 -08001126 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1127 });
1128 vlanPortMap.removeAll(VlanId.NONE);
1129
1130 return vlanPortMap;
1131 }
1132
1133 /**
Charles Chan59cc16d2017-02-02 16:20:42 -08001134 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -08001135 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -07001136 *
1137 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -08001138 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -08001139 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -07001140 */
Charles Chan65238242017-06-22 18:03:14 -07001141 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -07001142 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -08001143 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1144 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001145 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -08001146 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -08001147 + "device {} not found", deviceId);
1148 return -1;
1149 }
1150 }
1151
1152 /**
1153 * Returns the next objective ID for the given portNumber, given the treatment.
1154 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -07001155 * would result in different objectives. If the next object does not exist,
1156 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -08001157 *
1158 * @param deviceId Device ID
1159 * @param portNum port number on device for which NextObjective is queried
1160 * @param treatment the actions to apply on the packets (should include outport)
1161 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -07001162 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -07001163 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -08001164 */
1165 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1166 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -07001167 TrafficSelector meta,
1168 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -08001169 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1170 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -07001171 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -08001172 } else {
Charles Chane849c192016-01-11 18:28:54 -08001173 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1174 + " not found", deviceId);
1175 return -1;
1176 }
1177 }
1178
Saurav Dasc88d4662017-05-15 15:34:25 -07001179 /**
1180 * Returns the group handler object for the specified device id.
1181 *
1182 * @param devId the device identifier
1183 * @return the groupHandler object for the device id, or null if not found
1184 */
Charles Chan65238242017-06-22 18:03:14 -07001185 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001186 return groupHandlerMap.get(devId);
1187 }
1188
1189 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001190 * Returns the default routing handler object.
1191 *
1192 * @return the default routing handler object
1193 */
1194 public DefaultRoutingHandler getRoutingHandler() {
1195 return defaultRoutingHandler;
1196 }
1197
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001198 /**
1199 * Returns new dummy VLAN ID.
1200 * Dummy VLAN ID should be unique in each connect point.
1201 *
1202 * @param cp connect point
1203 * @param ipAddress IP address
1204 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1205 */
1206 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1207 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1208 dummyVlanIdStore.entrySet().stream().filter(entry ->
1209 (entry.getKey()).connectPoint().equals(cp))
1210 .map(Map.Entry::getValue)
1211 .collect(Collectors.toSet()));
1212
1213 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1214 i -> VlanId.vlanId((short) (i & 0xFFFF))
1215 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1216
1217 if (!dummyVlanId.equals(VlanId.NONE)) {
1218 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1219 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1220 } else {
1221 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1222 }
1223 return dummyVlanId;
1224 }
1225
1226
sanghob35a6192015-04-01 13:05:26 -07001227 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001228 @Override
1229 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -07001230 packetExecutor.execute(() -> processPacketInternal(context));
1231 }
sanghob35a6192015-04-01 13:05:26 -07001232
Charles Chan07f15f22018-05-08 21:35:50 -07001233 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001234 if (context.isHandled()) {
1235 return;
1236 }
1237
1238 InboundPacket pkt = context.inPacket();
1239 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001240
1241 if (ethernet == null) {
1242 return;
1243 }
1244
Saurav Das7bcbe702017-06-13 15:35:54 -07001245 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1246 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001247 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001248 log.warn("Received unexpected ARP packet on {}",
1249 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001250 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001251 return;
sanghob35a6192015-04-01 13:05:26 -07001252 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001253 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1254 //ipHandler.addToPacketBuffer(ipv4Packet);
1255 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1256 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001257 } else {
Charles Chan50035632017-01-13 17:20:44 -08001258 // NOTE: We don't support IP learning at this moment so this
1259 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001260 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001261 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001262 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1263 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001264 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001265 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001266 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1267 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1268 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1269 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1270 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1271 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001272 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001273 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001274 }
1275 } else {
1276 // NOTE: We don't support IP learning at this moment so this
1277 // is not necessary. Also it causes duplication of DHCPv6 packets.
1278 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1279 }
sanghob35a6192015-04-01 13:05:26 -07001280 }
1281 }
1282 }
1283
sanghob35a6192015-04-01 13:05:26 -07001284 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001285 private Event event;
1286
1287 InternalEventHandler(Event event) {
1288 this.event = event;
1289 }
1290
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001291 @Override
sanghob35a6192015-04-01 13:05:26 -07001292 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001293 try {
1294 // TODO We should also change SR routing and PW to listen to TopologyEvents
1295 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1296 event.type() == LinkEvent.Type.LINK_UPDATED) {
1297 linkHandler.processLinkAdded((Link) event.subject());
1298 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1299 linkHandler.processLinkRemoved((Link) event.subject());
1300 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1301 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1302 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1303 DeviceId deviceId = ((Device) event.subject()).id();
1304 if (deviceService.isAvailable(deviceId)) {
1305 log.info("** DEVICE UP Processing device event {} "
1306 + "for available device {}",
1307 event.type(), ((Device) event.subject()).id());
1308 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001309 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001310 log.info(" ** DEVICE DOWN Processing device event {}"
1311 + " for unavailable device {}",
1312 event.type(), ((Device) event.subject()).id());
1313 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001314 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001315 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1316 // typically these calls come when device is added first time
1317 // so port filtering rules are handled at the device_added event.
1318 // port added calls represent all ports on the device,
1319 // enabled or not.
1320 log.trace("** PORT ADDED {}/{} -> {}",
1321 ((DeviceEvent) event).subject().id(),
1322 ((DeviceEvent) event).port().number(),
1323 event.type());
1324 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1325 // these calls happen for every subsequent event
1326 // ports enabled, disabled, switch goes away, comes back
1327 log.info("** PORT UPDATED {}/{} -> {}",
1328 event.subject(),
1329 ((DeviceEvent) event).port(),
1330 event.type());
Saurav Das9a554292018-04-27 18:42:30 -07001331 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001332 ((DeviceEvent) event).port());
1333 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1334 // Process topology event, needed for all modules relying on
1335 // topology service for path computation
1336 TopologyEvent topologyEvent = (TopologyEvent) event;
1337 log.info("Processing topology event {}, topology age {}, reasons {}",
1338 event.type(), topologyEvent.subject().time(),
1339 topologyEvent.reasons().size());
1340 topologyHandler.processTopologyChange(topologyEvent.reasons());
1341 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1342 hostHandler.processHostAddedEvent((HostEvent) event);
1343 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1344 hostHandler.processHostMovedEvent((HostEvent) event);
1345 routeHandler.processHostMovedEvent((HostEvent) event);
1346 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1347 hostHandler.processHostRemovedEvent((HostEvent) event);
1348 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1349 hostHandler.processHostUpdatedEvent((HostEvent) event);
1350 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1351 routeHandler.processRouteAdded((RouteEvent) event);
1352 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1353 routeHandler.processRouteUpdated((RouteEvent) event);
1354 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1355 routeHandler.processRouteRemoved((RouteEvent) event);
1356 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1357 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1358 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1359 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1360 event.type() == McastEvent.Type.SINKS_ADDED ||
1361 event.type() == McastEvent.Type.SINKS_REMOVED ||
1362 event.type() == McastEvent.Type.ROUTE_ADDED ||
1363 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1364 mcastHandler.processMcastEvent((McastEvent) event);
1365 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1366 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1367 Class configClass = netcfgEvent.configClass();
1368 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1369 appCfgHandler.processAppConfigAdded(netcfgEvent);
1370 log.info("App config event .. configuring network");
1371 cfgListener.configureNetwork();
1372 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1373 log.info("Segment Routing Device Config added for {}", event.subject());
1374 cfgListener.configureNetwork();
1375 } else if (configClass.equals(XConnectConfig.class)) {
1376 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1377 } else if (configClass.equals(InterfaceConfig.class)) {
1378 log.info("Interface Config added for {}", event.subject());
1379 cfgListener.configureNetwork();
1380 } else {
1381 log.error("Unhandled config class: {}", configClass);
1382 }
1383 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1384 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1385 Class configClass = netcfgEvent.configClass();
1386 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1387 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1388 log.info("App config event .. configuring network");
1389 cfgListener.configureNetwork();
1390 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1391 log.info("Segment Routing Device Config updated for {}", event.subject());
1392 createOrUpdateDeviceConfiguration();
1393 } else if (configClass.equals(XConnectConfig.class)) {
1394 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1395 } else if (configClass.equals(InterfaceConfig.class)) {
1396 log.info("Interface Config updated for {}", event.subject());
1397 createOrUpdateDeviceConfiguration();
1398 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1399 (InterfaceConfig) netcfgEvent.prevConfig().get());
1400 } else {
1401 log.error("Unhandled config class: {}", configClass);
1402 }
1403 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1404 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1405 Class configClass = netcfgEvent.configClass();
1406 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1407 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1408 log.info("App config event .. configuring network");
1409 cfgListener.configureNetwork();
1410 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1411 // TODO Handle sr device config removal
1412 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1413 } else if (configClass.equals(XConnectConfig.class)) {
1414 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1415 } else if (configClass.equals(InterfaceConfig.class)) {
1416 // TODO Handle interface removal
1417 log.info("InterfaceConfig removal is not handled in current implementation");
1418 } else {
1419 log.error("Unhandled config class: {}", configClass);
1420 }
Saurav Das201762d2018-04-21 17:19:48 -07001421 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1422 MastershipEvent me = (MastershipEvent) event;
1423 DeviceId deviceId = me.subject();
1424 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1425 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1426 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1427 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1428 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1429 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001430 } else {
1431 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001432 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001433 } catch (Exception e) {
1434 log.error("SegmentRouting event handler thread thrown an exception: {}",
1435 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001436 }
sanghob35a6192015-04-01 13:05:26 -07001437 }
1438 }
1439
Saurav Das45f48152018-01-18 12:07:33 -08001440 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001441 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001442
1443 // NOTE: Punt ARP/NDP even when the device is not configured.
1444 // Host learning without network config is required for CORD config generator.
1445 routingRulePopulator.populateIpPunts(device.id());
1446 routingRulePopulator.populateArpNdpPunts(device.id());
1447
Charles Chan0b4e6182015-11-03 10:42:14 -08001448 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001449 log.warn("Device configuration unavailable. Device {} will be "
1450 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001451 return;
1452 }
Charles Chan2199c302016-04-23 17:36:10 -07001453 processDeviceAddedInternal(device.id());
1454 }
1455
1456 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001457 // Irrespective of whether the local is a MASTER or not for this device,
1458 // we need to create a SR-group-handler instance. This is because in a
1459 // multi-instance setup, any instance can initiate forwarding/next-objectives
1460 // for any switch (even if this instance is a SLAVE or not even connected
1461 // to the switch). To handle this, a default-group-handler instance is necessary
1462 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001463 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1464 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001465 DefaultGroupHandler groupHandler;
1466 try {
1467 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001468 createGroupHandler(deviceId,
1469 appId,
1470 deviceConfiguration,
1471 linkService,
1472 flowObjectiveService,
1473 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001474 } catch (DeviceConfigNotFoundException e) {
1475 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1476 return;
1477 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001478 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001479 deviceId);
1480 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001481 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001482
Charles Chan2199c302016-04-23 17:36:10 -07001483 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001484 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001485 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001486 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001487 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001488 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001489 }
Charles Chan5270ed02016-01-30 23:22:37 -08001490
Charles Chan03a73e02016-10-24 14:52:01 -07001491 appCfgHandler.init(deviceId);
Charles Chan94549652018-04-29 18:11:37 -07001492 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1493 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001494 }
1495
Saurav Das80980c72016-03-23 11:22:49 -07001496 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001497 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001498 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001499 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001500 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001501 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001502 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001503 portNextObjStore.entrySet().stream()
1504 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001505 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001506 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001507
Saurav Dasceccf242017-08-03 18:30:35 -07001508 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1509 if (gh != null) {
1510 gh.shutdown();
1511 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001512 // Note that a switch going down is associated with all of its links
1513 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001514 // while the link-downs are ignored. We cannot rely on the ordering of
1515 // events - i.e we cannot expect all link-downs to come before the
1516 // switch down - so we purge all seen-links for the switch before
1517 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001518 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001519 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001520 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001521 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001522
1523 // Cleanup all internal groupHandler stores for this device. Should be
1524 // done after all rerouting or rehashing has been completed
1525 groupHandlerMap.entrySet()
1526 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001527 }
1528
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001529 /**
1530 * Purge the destinationSet nextObjective store of entries with this device
1531 * as key. Erases app-level knowledge of hashed groups in this device.
1532 *
1533 * @param devId the device identifier
1534 */
Saurav Das201762d2018-04-21 17:19:48 -07001535 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001536 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das201762d2018-04-21 17:19:48 -07001537 dsNextObjStore.entrySet().stream()
1538 .filter(entry -> entry.getKey().deviceId().equals(devId))
1539 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1540 }
1541
Saurav Das9a554292018-04-27 18:42:30 -07001542 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001543 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1544 log.warn("Device configuration uploading. Not handling port event for"
1545 + "dev: {} port: {}", device.id(), port.number());
1546 return;
1547 }
Saurav Das018605f2017-02-18 14:05:44 -08001548
Saurav Das9a554292018-04-27 18:42:30 -07001549 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1550 lastEdgePortEvent = Instant.now();
1551 }
1552
Saurav Das018605f2017-02-18 14:05:44 -08001553 if (!mastershipService.isLocalMaster(device.id())) {
1554 log.debug("Not master for dev:{} .. not handling port updated event"
1555 + "for port {}", device.id(), port.number());
1556 return;
1557 }
Saurav Das9a554292018-04-27 18:42:30 -07001558 processPortUpdated(device.id(), port);
1559 }
Saurav Das018605f2017-02-18 14:05:44 -08001560
Saurav Das9a554292018-04-27 18:42:30 -07001561 /**
1562 * Adds or remove filtering rules for the given switchport. If switchport is
1563 * an edge facing port, additionally handles host probing and broadcast
1564 * rules. Must be called by local master of device.
1565 *
1566 * @param deviceId the device identifier
1567 * @param port the port to update
1568 */
1569 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001570 // first we handle filtering rules associated with the port
1571 if (port.isEnabled()) {
1572 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das9a554292018-04-27 18:42:30 -07001573 deviceId, port.number());
1574 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001575 } else {
1576 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das9a554292018-04-27 18:42:30 -07001577 deviceId, port.number());
1578 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001579 }
Saurav Das1a129a02016-11-18 15:21:57 -08001580
1581 // portUpdated calls are for ports that have gone down or up. For switch
1582 // to switch ports, link-events should take care of any re-routing or
1583 // group editing necessary for port up/down. Here we only process edge ports
1584 // that are already configured.
Saurav Das9a554292018-04-27 18:42:30 -07001585 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan971d7ba2018-05-01 11:50:20 -07001586 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1587 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1588 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001589
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001590 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001591 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das9a554292018-04-27 18:42:30 -07001592 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001593 return;
1594 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001595 if (untaggedVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001596 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001597 }
1598 if (nativeVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001599 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001600 }
1601 if (!taggedVlans.isEmpty()) {
Saurav Das9a554292018-04-27 18:42:30 -07001602 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001603 }
Saurav Das1a129a02016-11-18 15:21:57 -08001604 }
1605
Saurav Das9a554292018-04-27 18:42:30 -07001606 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001607 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001608 boolean portUp = port.isEnabled();
1609 if (portUp) {
Saurav Das9a554292018-04-27 18:42:30 -07001610 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001611 port.number(), vlanId);
Charles Chan94549652018-04-29 18:11:37 -07001612 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001613 } else {
Saurav Das9a554292018-04-27 18:42:30 -07001614 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001615 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001616 }
1617
Saurav Das9a554292018-04-27 18:42:30 -07001618 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001619 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001620 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001621 } else {
1622 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das9a554292018-04-27 18:42:30 -07001623 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001624 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001625 }
1626 }
sangho1e575652015-05-14 00:39:53 -07001627
Charles Chan27fe1a52017-10-20 16:06:55 -07001628 private void createOrUpdateDeviceConfiguration() {
1629 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001630 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001631 deviceConfiguration = new DeviceConfiguration(this);
1632 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001633 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001634 deviceConfiguration.updateConfig();
1635 }
1636 }
1637
Charles Chan50bb6ef2018-04-18 18:41:05 -07001638 private void createOrUpdateDefaultRoutingHandler() {
1639 if (defaultRoutingHandler == null) {
1640 log.info("Creating new DefaultRoutingHandler");
1641 defaultRoutingHandler = new DefaultRoutingHandler(this);
1642 } else {
1643 log.info("Updating DefaultRoutingHandler");
1644 defaultRoutingHandler.update(this);
1645 }
1646 }
1647
Pier Ventre10bd8d12016-11-26 21:05:22 -08001648 /**
1649 * Registers the given connect point with the NRS, this is necessary
1650 * to receive the NDP and ARP packets from the NRS.
1651 *
1652 * @param portToRegister connect point to register
1653 */
1654 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001655 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001656 portToRegister,
1657 neighbourHandler,
1658 appId
1659 );
1660 }
1661
Charles Chand6832882015-10-05 17:50:33 -07001662 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001663 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001664 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001665
Charles Chane849c192016-01-11 18:28:54 -08001666 /**
1667 * Constructs the internal network config listener.
1668 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001669 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001670 */
Charles Chan65238242017-06-22 18:03:14 -07001671 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001672 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001673 }
1674
Charles Chane849c192016-01-11 18:28:54 -08001675 /**
1676 * Reads network config and initializes related data structure accordingly.
1677 */
Charles Chan47933752017-11-30 15:37:50 -08001678 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001679 log.info("Configuring network ...");
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001680
1681 // Setting handling of network configuration events completable future
1682 // The completable future is needed because of the async behaviour of the configureNetwork,
1683 // listener registration and event arrival
1684 // Enables us to buffer the events and execute them when the configure network is done.
1685 networkConfigCompletion = new CompletableFuture<>();
1686
1687 // add a small delay to absorb multiple network config added notifications
1688 if (!programmingScheduled.get()) {
1689 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1690 programmingScheduled.set(true);
1691 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1692 }
1693
Charles Chan27fe1a52017-10-20 16:06:55 -07001694 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001695
Charles Chan2c15aca2016-11-09 20:51:44 -08001696 arpHandler = new ArpHandler(srManager);
1697 icmpHandler = new IcmpHandler(srManager);
1698 ipHandler = new IpHandler(srManager);
1699 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chan50bb6ef2018-04-18 18:41:05 -07001700 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001701
1702 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1703 groupHandlerMap, tunnelStore);
1704 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1705 flowObjectiveService,
1706 tunnelHandler, policyStore);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001707 networkConfigCompletion.complete(true);
1708
Charles Chan2199c302016-04-23 17:36:10 -07001709 mcastHandler.init();
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001710
Charles Chan4636be02015-10-07 14:21:45 -07001711 }
1712
Charles Chand6832882015-10-05 17:50:33 -07001713 @Override
1714 public void event(NetworkConfigEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001715 if (mainEventExecutor == null) {
1716 return;
1717 }
Charles Chan7a888e82018-03-21 16:57:47 -07001718 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1719 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1720 switch (event.type()) {
1721 case CONFIG_ADDED:
1722 case CONFIG_UPDATED:
1723 case CONFIG_REMOVED:
1724 log.trace("Schedule Network Config event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001725 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1726 mainEventExecutor.execute(new InternalEventHandler(event));
1727 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001728 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001729 }
Charles Chan7a888e82018-03-21 16:57:47 -07001730 break;
1731 default:
1732 break;
Charles Chand6832882015-10-05 17:50:33 -07001733 }
1734 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001735
Charles Chan50443e82018-01-03 16:26:32 -08001736 @Override
1737 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001738 if (event.type() == CONFIG_REGISTERED ||
1739 event.type() == CONFIG_UNREGISTERED) {
1740 log.debug("Ignore event {} due to type mismatch", event);
1741 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001742 }
Saurav Dase7f51012018-02-09 17:26:45 -08001743
1744 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1745 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1746 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001747 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001748 log.debug("Ignore event {} due to class mismatch", event);
1749 return false;
1750 }
1751
1752 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001753 }
1754
Saurav Das7bcbe702017-06-13 15:35:54 -07001755 private final class ConfigChange implements Runnable {
1756 @Override
1757 public void run() {
1758 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001759 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001760 for (Device device : deviceService.getDevices()) {
1761 processDeviceAdded(device);
1762 }
1763 defaultRoutingHandler.startPopulationProcess();
1764 }
1765 }
Charles Chand6832882015-10-05 17:50:33 -07001766 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001767
Charles Chan7a888e82018-03-21 16:57:47 -07001768 private class InternalLinkListener implements LinkListener {
1769 @Override
1770 public void event(LinkEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001771 if (mainEventExecutor == null) {
1772 return;
1773 }
Charles Chan7a888e82018-03-21 16:57:47 -07001774 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1775 event.type() == LinkEvent.Type.LINK_UPDATED ||
1776 event.type() == LinkEvent.Type.LINK_REMOVED) {
1777 log.trace("Schedule Link event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001778 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1779 mainEventExecutor.execute(new InternalEventHandler(event));
1780 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001781 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001782 }
Charles Chan7a888e82018-03-21 16:57:47 -07001783 }
1784 }
1785 }
1786
1787 private class InternalDeviceListener implements DeviceListener {
1788 @Override
1789 public void event(DeviceEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001790 if (mainEventExecutor == null) {
1791 return;
1792 }
Charles Chan7a888e82018-03-21 16:57:47 -07001793 switch (event.type()) {
1794 case DEVICE_ADDED:
1795 case PORT_UPDATED:
1796 case PORT_ADDED:
1797 case DEVICE_UPDATED:
1798 case DEVICE_AVAILABILITY_CHANGED:
1799 log.trace("Schedule Device event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001800 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1801 mainEventExecutor.execute(new InternalEventHandler(event));
1802 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001803 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001804 }
Charles Chan7a888e82018-03-21 16:57:47 -07001805 break;
1806 default:
1807 }
1808 }
1809 }
1810
1811 private class InternalTopologyListener implements TopologyListener {
1812 @Override
1813 public void event(TopologyEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001814 if (mainEventExecutor == null) {
1815 return;
1816 }
Charles Chan7a888e82018-03-21 16:57:47 -07001817 switch (event.type()) {
1818 case TOPOLOGY_CHANGED:
1819 log.trace("Schedule Topology event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001820 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1821 mainEventExecutor.execute(new InternalEventHandler(event));
1822 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001823 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001824 }
Charles Chan7a888e82018-03-21 16:57:47 -07001825 break;
1826 default:
1827 }
1828 }
1829 }
1830
Charles Chan68aa62d2015-11-09 16:37:23 -08001831 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001832 @Override
1833 public void event(HostEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001834 if (hostEventExecutor == null) {
1835 return;
1836 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001837 switch (event.type()) {
1838 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001839 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001840 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001841 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001842 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001843 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001844 break;
1845 default:
1846 log.warn("Unsupported host event type: {}", event.type());
1847 break;
1848 }
1849 }
1850 }
1851
Charles Chand55e84d2016-03-30 17:54:24 -07001852 private class InternalMcastListener implements McastListener {
1853 @Override
1854 public void event(McastEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001855 if (mcastEventExecutor == null) {
1856 return;
1857 }
Charles Chand55e84d2016-03-30 17:54:24 -07001858 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001859 case SOURCES_ADDED:
1860 case SOURCES_REMOVED:
1861 case SINKS_ADDED:
1862 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001863 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001864 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001865 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001866 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001867 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001868 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001869 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001870 break;
1871 }
1872 }
1873 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001874
Charles Chan03a73e02016-10-24 14:52:01 -07001875 private class InternalRouteEventListener implements RouteListener {
1876 @Override
1877 public void event(RouteEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001878 if (routeEventExecutor == null) {
1879 return;
1880 }
Charles Chan03a73e02016-10-24 14:52:01 -07001881 switch (event.type()) {
1882 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001883 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001884 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001885 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001886 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001887 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001888 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001889 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001890 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001891 break;
1892 }
1893 }
1894 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001895
Charles Chan50bb6ef2018-04-18 18:41:05 -07001896 private class InternalMastershipListener implements MastershipListener {
1897 @Override
1898 public void event(MastershipEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001899 if (mainEventExecutor == null) {
1900 return;
1901 }
Charles Chan50bb6ef2018-04-18 18:41:05 -07001902 switch (event.type()) {
Saurav Das201762d2018-04-21 17:19:48 -07001903 case MASTER_CHANGED:
1904 log.debug("Mastership event: {}/{}", event.subject(),
1905 event.roleInfo());
1906 mainEventExecutor.execute(new InternalEventHandler(event));
1907 break;
1908 case BACKUPS_CHANGED:
1909 case SUSPENDED:
1910 default:
1911 log.debug("Mastership event type {} not handled", event.type());
1912 break;
Charles Chan50bb6ef2018-04-18 18:41:05 -07001913 }
1914 }
1915 }
1916
Saurav Das201762d2018-04-21 17:19:48 -07001917 class InternalClusterListener implements ClusterEventListener {
1918 private Instant lastClusterEvent = Instant.EPOCH;
1919
1920 long timeSinceLastClusterEvent() {
1921 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1922 }
1923
1924 @Override
1925 public void event(ClusterEvent event) {
1926 switch (event.type()) {
1927 case INSTANCE_ACTIVATED:
1928 case INSTANCE_ADDED:
1929 case INSTANCE_READY:
1930 log.debug("Cluster event {} ignored", event.type());
1931 break;
1932 case INSTANCE_DEACTIVATED:
1933 case INSTANCE_REMOVED:
1934 log.info("** Cluster event {}", event.type());
1935 lastClusterEvent = Instant.now();
1936 break;
1937 default:
1938 break;
1939 }
1940
1941 }
1942
1943 }
1944
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001945 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1946 try {
1947 Set<Interface> intfs = conf.getInterfaces();
1948 Set<Interface> prevIntfs = prevConf.getInterfaces();
1949
1950 // Now we only handle one interface config at each port.
1951 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1952 log.warn("Interface update aborted - one at a time is allowed, " +
1953 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1954 return;
1955 }
1956
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001957 //The system is in an incoherent state, abort
1958 if (defaultRoutingHandler == null) {
1959 log.warn("Interface update aborted, defaultRoutingHandler is null");
1960 return;
1961 }
1962
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001963 Interface intf = intfs.stream().findFirst().get();
1964 Interface prevIntf = prevIntfs.stream().findFirst().get();
1965
1966 DeviceId deviceId = intf.connectPoint().deviceId();
1967 PortNumber portNum = intf.connectPoint().port();
1968
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001969 removeSubnetConfig(prevIntf.connectPoint(),
1970 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1971 new HashSet<>(intf.ipAddressesList())));
1972
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001973 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1974 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1975 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1976 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1977 // Update filtering objective and L2IG group bucket
1978 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1979 } else {
1980 // RemoveVlanNative
1981 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1982 }
1983 }
1984
1985 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1986 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1987 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1988 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1989 // Update filtering objective and L2IG group bucket
1990 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1991 } else {
1992 // RemoveVlanUntagged
1993 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1994 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001995 }
1996
1997 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1998 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001999 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2000 .filter(i -> !intf.vlanUntagged().equals(i))
2001 .filter(i -> !intf.vlanNative().equals(i))
2002 .forEach(vlanId -> updateVlanConfigInternal(
2003 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002004 }
2005
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002006 if (!intf.vlanNative().equals(VlanId.NONE)
2007 && !prevIntf.vlanNative().equals(intf.vlanNative())
2008 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2009 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2010 // Update filtering objective and L2IG group bucket
2011 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2012 } else {
2013 // AddVlanNative
2014 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2015 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002016 }
2017
2018 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2019 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002020 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2021 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2022 .filter(i -> !prevIntf.vlanNative().equals(i))
2023 .forEach(vlanId -> updateVlanConfigInternal(
2024 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002025 );
2026 }
2027
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002028 if (!intf.vlanUntagged().equals(VlanId.NONE)
2029 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2030 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2031 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2032 // Update filtering objective and L2IG group bucket
2033 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2034 } else {
2035 // AddVlanUntagged
2036 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2037 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002038 }
2039 addSubnetConfig(prevIntf.connectPoint(),
2040 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2041 new HashSet<>(prevIntf.ipAddressesList())));
2042 } catch (ConfigException e) {
2043 log.error("Error in configuration");
2044 }
2045 }
2046
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002047 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2048 VlanId vlanId, boolean pushVlan) {
2049 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2050 if (grpHandler == null) {
2051 log.warn("Failed to retrieve group handler for device {}", deviceId);
2052 return;
2053 }
2054
2055 // Update filtering objective for a single port
2056 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2057 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2058
2059 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2060 // Update L2IG bucket of the port
2061 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2062 } else {
2063 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2064 }
2065 }
2066
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002067 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2068 VlanId vlanId, boolean pushVlan, boolean install) {
2069 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2070 if (grpHandler == null) {
2071 log.warn("Failed to retrieve group handler for device {}", deviceId);
2072 return;
2073 }
2074
2075 // Update filtering objective for a single port
2076 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2077
2078 // Update filtering objective for multicast ingress port
2079 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2080
2081 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2082
2083 if (nextId != -1 && !install) {
2084 // Update next objective for a single port as an output port
2085 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002086 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002087 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan94549652018-04-29 18:11:37 -07002088 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2089 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002090 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2091 // only if there is no port configured on that VLAN ID
2092 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2093 // Remove broadcast forwarding rule for the VLAN
2094 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2095 // Remove L2FG for VLAN
2096 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2097 } else {
2098 // Remove L2IG of the port
2099 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2100 }
2101 } else if (install) {
2102 if (nextId != -1) {
2103 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002104 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002105 } else {
2106 // Create L2FG for VLAN
2107 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2108 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2109 }
Charles Chan94549652018-04-29 18:11:37 -07002110 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2111 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002112 } else {
2113 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2114 }
2115 }
2116
2117 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2118 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2119 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2120
2121 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2122 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2123 .filter(intf -> !intf.connectPoint().equals(cp))
2124 .flatMap(intf -> intf.ipAddressesList().stream())
2125 .collect(Collectors.toSet());
2126 // 1. Partial subnet population
2127 // Remove routing rules for removed subnet from previous configuration,
2128 // which does not also exist in other interfaces in the same device
2129 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2130 .map(InterfaceIpAddress::subnetAddress)
2131 .collect(Collectors.toSet());
2132
2133 defaultRoutingHandler.revokeSubnet(
2134 ipPrefixSet.stream()
2135 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2136 .collect(Collectors.toSet()));
2137
2138 // 2. Interface IP punts
2139 // Remove IP punts for old Intf address
2140 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2141 .map(InterfaceIpAddress::ipAddress)
2142 .collect(Collectors.toSet());
2143 ipAddressSet.stream()
2144 .map(InterfaceIpAddress::ipAddress)
2145 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2146 .forEach(interfaceIpAddress ->
2147 routingRulePopulator.revokeSingleIpPunts(
2148 cp.deviceId(), interfaceIpAddress));
2149
2150 // 3. Host unicast routing rule
2151 // Remove unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002152 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002153 }
2154
2155 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2156 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2157 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2158
2159 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2160 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2161 .filter(intf -> !intf.connectPoint().equals(cp))
2162 .flatMap(intf -> intf.ipAddressesList().stream())
2163 .collect(Collectors.toSet());
2164 // 1. Partial subnet population
2165 // Add routing rules for newly added subnet, which does not also exist in
2166 // other interfaces in the same device
2167 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2168 .map(InterfaceIpAddress::subnetAddress)
2169 .collect(Collectors.toSet());
2170
2171 defaultRoutingHandler.populateSubnet(
2172 Collections.singleton(cp),
2173 ipPrefixSet.stream()
2174 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2175 .collect(Collectors.toSet()));
2176
2177 // 2. Interface IP punts
2178 // Add IP punts for new Intf address
2179 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2180 .map(InterfaceIpAddress::ipAddress)
2181 .collect(Collectors.toSet());
2182 ipAddressSet.stream()
2183 .map(InterfaceIpAddress::ipAddress)
2184 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2185 .forEach(interfaceIpAddress ->
2186 routingRulePopulator.populateSingleIpPunts(
2187 cp.deviceId(), interfaceIpAddress));
2188
2189 // 3. Host unicast routing rule
2190 // Add unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002191 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002192 }
sanghob35a6192015-04-01 13:05:26 -07002193}