blob: ed2a6785f6a45ead9369d77532555d5d1ecc6e96 [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 Chan68aa62d2015-11-09 16:37:23 -080078import org.onosproject.net.host.HostEvent;
79import org.onosproject.net.host.HostListener;
Charles Chanff79dd92018-06-01 16:33:48 -070080import org.onosproject.net.host.HostProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080081import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070082import org.onosproject.net.host.InterfaceIpAddress;
Pier96f63cb2018-04-17 16:29:56 +020083import org.onosproject.net.intent.WorkPartitionService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070084import org.onosproject.net.intf.Interface;
85import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080086import org.onosproject.net.link.LinkEvent;
87import org.onosproject.net.link.LinkListener;
88import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070089import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080090import org.onosproject.net.packet.InboundPacket;
91import org.onosproject.net.packet.PacketContext;
92import org.onosproject.net.packet.PacketProcessor;
93import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010094import org.onosproject.net.topology.TopologyEvent;
95import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070096import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070097import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070098import org.onosproject.routeservice.RouteEvent;
99import org.onosproject.routeservice.RouteListener;
100import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700101import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
102import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800103import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700105import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700106import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700107import org.onosproject.segmentrouting.grouphandler.DestinationSet;
108import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100109import org.onosproject.segmentrouting.mcast.McastHandler;
110import org.onosproject.segmentrouting.mcast.McastRole;
Pier3e793752018-04-19 16:47:06 +0200111import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700112import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800116
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800117import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700118import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800119import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
121
Saurav Das7bcbe702017-06-13 15:35:54 -0700122import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700123import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Pier3e793752018-04-19 16:47:06 +0200124import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700125import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800126import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700127import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chanc7b3c452018-06-19 20:31:57 -0700128import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700129import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700130import org.onosproject.store.service.EventuallyConsistentMap;
131import org.onosproject.store.service.EventuallyConsistentMapBuilder;
132import org.onosproject.store.service.StorageService;
133import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800134import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700135import org.slf4j.Logger;
136import org.slf4j.LoggerFactory;
137
Saurav Das201762d2018-04-21 17:19:48 -0700138import java.time.Instant;
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700139import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800140import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800141import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800142import java.util.HashSet;
143import java.util.List;
144import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800145import java.util.Optional;
146import java.util.Set;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200147import java.util.concurrent.CompletableFuture;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800148import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200149import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan07f15f22018-05-08 21:35:50 -0700150import java.util.concurrent.ExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800151import java.util.concurrent.Executors;
152import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800153import java.util.concurrent.TimeUnit;
154import java.util.concurrent.atomic.AtomicBoolean;
155import java.util.stream.Collectors;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700156import java.util.stream.IntStream;
sanghob35a6192015-04-01 13:05:26 -0700157
Charles Chan3e783d02016-02-26 22:19:52 -0800158import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800159import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700160import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800161import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800163
Charles Chane849c192016-01-11 18:28:54 -0800164/**
165 * Segment routing manager.
166 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700167@Service
168@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700169public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700170
Charles Chan2c15aca2016-11-09 20:51:44 -0800171 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700172 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700173
174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700175 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700176
177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800178 private NeighbourResolutionService neighbourResolutionService;
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100181 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700182
183 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700184 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700185
186 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700187 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700188
189 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanff79dd92018-06-01 16:33:48 -0700190 HostProbingService probingService;
Charles Chan47933752017-11-30 15:37:50 -0800191
192 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100193 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700194
195 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800196 DeviceAdminService deviceAdminService;
197
198 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800199 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700200
201 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100202 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700203
Charles Chan5270ed02016-01-30 23:22:37 -0800204 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800205 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700206
207 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800208 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700209
210 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100211 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700212
213 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800214 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700215
216 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700217 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800218
219 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800220 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800221
Saurav Das80980c72016-03-23 11:22:49 -0700222 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800223 public InterfaceService interfaceService;
224
Pier Luigieba73a02018-01-16 10:47:50 +0100225 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
226 public ClusterService clusterService;
227
228 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier96f63cb2018-04-17 16:29:56 +0200229 public WorkPartitionService workPartitionService;
Pier Luigieba73a02018-01-16 10:47:50 +0100230
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700231 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
232 public LeadershipService leadershipService;
233
Charles Chanc7b3c452018-06-19 20:31:57 -0700234 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
235 public XconnectService xconnectService;
236
Charles Chan47933752017-11-30 15:37:50 -0800237 @Property(name = "activeProbing", boolValue = true,
238 label = "Enable active probing to discover dual-homed hosts.")
239 boolean activeProbing = true;
240
Saurav Das9a554292018-04-27 18:42:30 -0700241 @Property(name = "singleHomedDown", boolValue = false,
242 label = "Enable administratively taking down single-homed hosts "
243 + "when all uplinks are gone")
244 boolean singleHomedDown = false;
245
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700246 @Property(name = "respondToUnknownHosts", boolValue = true,
247 label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
248 boolean respondToUnknownHosts = true;
249
Charles Chanb67dfdd2018-07-24 16:40:35 -0700250 @Property(name = "routeDoubleTaggedHosts", boolValue = false,
251 label = "Program flows and groups to pop and route double tagged hosts")
252 boolean routeDoubleTaggedHosts = false;
Charles Chan57465d32018-07-19 14:55:31 -0700253
Saurav Das09c2c4d2018-08-13 15:34:26 -0700254 private static final int DEFAULT_INTERNAL_VLAN = 4094;
255 @Property(name = "defaultInternalVlan", intValue = DEFAULT_INTERNAL_VLAN,
256 label = "internal vlan assigned by default to unconfigured ports")
257 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN;
258
259 private static final int PW_TRANSPORT_VLAN = 4090;
260 @Property(name = "pwTransportVlan", intValue = PW_TRANSPORT_VLAN,
261 label = "vlan used for transport of pseudowires between switches")
262 private int pwTransportVlan = PW_TRANSPORT_VLAN;
263
Charles Chan03a73e02016-10-24 14:52:01 -0700264 ArpHandler arpHandler = null;
265 IcmpHandler icmpHandler = null;
266 IpHandler ipHandler = null;
267 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700268 ApplicationId appId;
269 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700270
Charles Chan03a73e02016-10-24 14:52:01 -0700271 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700272 private TunnelHandler tunnelHandler = null;
273 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700274 private InternalPacketProcessor processor = null;
275 private InternalLinkListener linkListener = null;
276 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700277 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100278 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800279 McastHandler mcastHandler = null;
280 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800281 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800282 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800283 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800284 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100285 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800286 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700287 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
288 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700289 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100290 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700291 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das201762d2018-04-21 17:19:48 -0700292 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200293 //Completable future for network configuration process to buffer config events handling during activation
294 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan10b2fee2018-04-21 00:44:29 -0700295 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sanghob35a6192015-04-01 13:05:26 -0700296
Charles Chan9b7217c2018-04-05 16:31:15 -0700297 // Handles device, link, topology and network config events
Charles Chan50bb6ef2018-04-18 18:41:05 -0700298 private ScheduledExecutorService mainEventExecutor;
sanghob35a6192015-04-01 13:05:26 -0700299
Charles Chan50bb6ef2018-04-18 18:41:05 -0700300 // Handles host, route and mcast events respectively
301 private ScheduledExecutorService hostEventExecutor;
302 private ScheduledExecutorService routeEventExecutor;
303 private ScheduledExecutorService mcastEventExecutor;
Charles Chan07f15f22018-05-08 21:35:50 -0700304 private ExecutorService packetExecutor;
Charles Chan9b7217c2018-04-05 16:31:15 -0700305
306 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800307 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700308 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700309 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800310 */
Charles Chan47933752017-11-30 15:37:50 -0800311 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700312 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800313 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700314 * Per device next objective ID store with (device id + vlanid) as key.
315 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800316 */
Charles Chan47933752017-11-30 15:37:50 -0800317 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800318 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800319 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700320 * Per device next objective ID store with (device id + port + treatment + meta) as key.
321 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800322 */
Charles Chan47933752017-11-30 15:37:50 -0800323 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800324 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800325
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700326 /**
327 * Per port dummy VLAN ID store with (connect point + ip address) as key.
328 * Used to keep track on dummy VLAN ID allocation.
329 */
330 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
331 dummyVlanIdStore = null;
332
Saurav Das4ce45962015-11-24 23:21:05 -0800333 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
334 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700335
Saurav Das7bcbe702017-06-13 15:35:54 -0700336 private AtomicBoolean programmingScheduled = new AtomicBoolean();
337
Charles Chand55e84d2016-03-30 17:54:24 -0700338 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700339 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
340 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700341 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700342 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800343 public SegmentRoutingDeviceConfig createConfig() {
344 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700345 }
346 };
Pier Ventref34966c2016-11-07 16:21:04 -0800347
Charles Chand55e84d2016-03-30 17:54:24 -0700348 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700349 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
350 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700351 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800352 @Override
353 public SegmentRoutingAppConfig createConfig() {
354 return new SegmentRoutingAppConfig();
355 }
356 };
Pier Ventref34966c2016-11-07 16:21:04 -0800357
Charles Chanfc5c7802016-05-17 13:13:55 -0700358 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
359 new ConfigFactory<ApplicationId, XConnectConfig>(
360 SubjectFactories.APP_SUBJECT_FACTORY,
361 XConnectConfig.class, "xconnect") {
362 @Override
363 public XConnectConfig createConfig() {
364 return new XConnectConfig();
365 }
366 };
Pier Ventref34966c2016-11-07 16:21:04 -0800367
Charles Chand55e84d2016-03-30 17:54:24 -0700368 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700369 new ConfigFactory<ApplicationId, McastConfig>(
370 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700371 McastConfig.class, "multicast") {
372 @Override
373 public McastConfig createConfig() {
374 return new McastConfig();
375 }
376 };
377
Charles Chan116188d2016-02-18 14:22:42 -0800378 /**
379 * Segment Routing App ID.
380 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800381 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das0e99e2b2015-10-28 12:39:42 -0700382
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700383 /**
384 * Minumum and maximum value of dummy VLAN ID to be allocated.
385 */
386 public static final int MIN_DUMMY_VLAN_ID = 2;
387 public static final int MAX_DUMMY_VLAN_ID = 4093;
388
Saurav Das9a554292018-04-27 18:42:30 -0700389 Instant lastEdgePortEvent = Instant.EPOCH;
390
sanghob35a6192015-04-01 13:05:26 -0700391 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800392 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800393 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700394
Charles Chan50bb6ef2018-04-18 18:41:05 -0700395 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
396 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
397 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
398 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan07f15f22018-05-08 21:35:50 -0700399 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chan50bb6ef2018-04-18 18:41:05 -0700400
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700401 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700402 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700403 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700404 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700405 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700406 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700407 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700408 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700409 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700410
Charles Chan59cc16d2017-02-02 16:20:42 -0800411 log.debug("Creating EC map vlannextobjectivestore");
412 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
413 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
414 vlanNextObjStore = vlanNextObjMapBuilder
415 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700416 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700417 .withTimestampProvider((k, v) -> new WallClockTimestamp())
418 .build();
419
Saurav Das4ce45962015-11-24 23:21:05 -0800420 log.debug("Creating EC map subnetnextobjectivestore");
421 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
422 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
423 portNextObjStore = portNextObjMapBuilder
424 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700425 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800426 .withTimestampProvider((k, v) -> new WallClockTimestamp())
427 .build();
428
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700429 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
430 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
431 dummyVlanIdStore = dummyVlanIdMapBuilder
432 .withName("dummyvlanidstore")
433 .withSerializer(createSerializer())
434 .withTimestampProvider((k, v) -> new WallClockTimestamp())
435 .build();
436
sangho0b2b6d12015-05-20 22:16:38 -0700437 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
438 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700439 tunnelStore = tunnelMapBuilder
440 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700441 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700442 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700443 .build();
444
445 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
446 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700447 policyStore = policyMapBuilder
448 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700449 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700450 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700451 .build();
452
Saurav Das80980c72016-03-23 11:22:49 -0700453 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800454 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700455 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800456 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800457 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
458 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700459 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800460 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700461 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800462 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800463 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
464 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800465 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
466 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700467 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700468 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700469 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
470 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800471 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
472 "staleLinkAge", "15000");
473 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
474 "allowDuplicateIps", "false");
Yi Tsengfe13f3e2018-08-19 03:09:54 +0800475 // For P4 switches
476 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
477 "fallbackFlowPollFrequency", "5");
478 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
479 "fallbackGroupPollFrequency", "5");
Charles Chan47933752017-11-30 15:37:50 -0800480 compCfgService.registerProperties(getClass());
481 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700482
Charles Chanb8e10c82015-10-14 11:24:40 -0700483 processor = new InternalPacketProcessor();
484 linkListener = new InternalLinkListener();
485 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700486 appCfgHandler = new AppConfigHandler(this);
487 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700488 mcastHandler = new McastHandler(this);
489 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800490 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700491 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800492 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800493 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100494 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700495
Charles Chan3e783d02016-02-26 22:19:52 -0800496 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700497 cfgService.registerConfigFactory(deviceConfigFactory);
498 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700499 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700500 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800501 log.info("Configuring network before adding listeners");
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200502
Charles Chan132393a2018-01-04 14:26:07 -0800503 cfgListener.configureNetwork();
504
Charles Chan5270ed02016-01-30 23:22:37 -0800505 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700506 packetService.addProcessor(processor, PacketProcessor.director(2));
507 linkService.addListener(linkListener);
508 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700509 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700510 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100511 topologyService.addListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700512 mastershipService.addListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700513 clusterService.addListener(clusterListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700514
Charles Chanb39777c2018-03-09 15:53:44 -0800515 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800516 l2TunnelHandler.init();
517
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200518 networkConfigCompletion.whenComplete((value, ex) -> {
519 //setting to null for easier fall through
520 networkConfigCompletion = null;
521 //process all queued events
Charles Chan10b2fee2018-04-21 00:44:29 -0700522 queuedEvents.forEach(event -> {
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200523 mainEventExecutor.execute(new InternalEventHandler(event));
524 });
525 });
526
sanghob35a6192015-04-01 13:05:26 -0700527 log.info("Started");
528 }
529
Saurav Das45f48152018-01-18 12:07:33 -0800530 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700531 return new KryoNamespace.Builder()
532 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700533 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800534 VlanNextObjectiveStoreKey.class,
535 DestinationSet.class,
Andreas Pantelopoulos67e09ae2018-05-29 13:11:14 -0700536 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800537 NextNeighbors.class,
538 Tunnel.class,
539 DefaultTunnel.class,
540 Policy.class,
541 TunnelPolicy.class,
542 Policy.Type.class,
543 PortNextObjectiveStoreKey.class,
544 XConnectStoreKey.class,
545 L2Tunnel.class,
546 L2TunnelPolicy.class,
547 DefaultL2Tunnel.class,
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700548 DefaultL2TunnelPolicy.class,
549 DummyVlanIdStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700550 );
551 }
552
sanghob35a6192015-04-01 13:05:26 -0700553 @Deactivate
554 protected void deactivate() {
Charles Chan50bb6ef2018-04-18 18:41:05 -0700555 mainEventExecutor.shutdown();
556 hostEventExecutor.shutdown();
557 routeEventExecutor.shutdown();
558 mcastEventExecutor.shutdown();
Charles Chan07f15f22018-05-08 21:35:50 -0700559 packetExecutor.shutdown();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700560
Ray Milkey749996b2018-05-11 09:59:19 -0700561 mainEventExecutor = null;
562 hostEventExecutor = null;
563 routeEventExecutor = null;
564 mcastEventExecutor = null;
565 packetExecutor = null;
566
Charles Chand6832882015-10-05 17:50:33 -0700567 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700568 cfgService.unregisterConfigFactory(deviceConfigFactory);
569 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700570 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700571 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800572 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700573
Charles Chanc7a8a682017-06-19 00:43:31 -0700574 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700575 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700576 linkService.removeListener(linkListener);
577 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700578 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700579 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100580 topologyService.removeListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700581 mastershipService.removeListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700582 clusterService.removeListener(clusterListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700583
Charles Chan0aa674e2017-02-23 15:44:08 -0800584 neighbourResolutionService.unregisterNeighbourHandlers(appId);
585
sanghob35a6192015-04-01 13:05:26 -0700586 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700587 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700588 deviceListener = null;
Charles Chan6577f612018-04-19 13:10:01 -0700589 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chanb8e10c82015-10-14 11:24:40 -0700590 groupHandlerMap.clear();
Saurav Dasc6ff8f02018-04-23 18:42:12 -0700591 defaultRoutingHandler.shutdown();
Charles Chanb8e10c82015-10-14 11:24:40 -0700592
Saurav Das7bcbe702017-06-13 15:35:54 -0700593 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800594 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700595 portNextObjStore.destroy();
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700596 dummyVlanIdStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700597 tunnelStore.destroy();
598 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100599
600 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700601 log.info("Stopped");
602 }
603
Charles Chan47933752017-11-30 15:37:50 -0800604 @Modified
605 private void modified(ComponentContext context) {
606 Dictionary<?, ?> properties = context.getProperties();
607 if (properties == null) {
608 return;
609 }
610
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700611 String strActiveProbing = Tools.get(properties, "activeProbing");
612 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan47933752017-11-30 15:37:50 -0800613 if (expectActiveProbing != activeProbing) {
614 activeProbing = expectActiveProbing;
615 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
616 }
Saurav Das9a554292018-04-27 18:42:30 -0700617
618 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
619 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
620 if (expectSingleHomedDown != singleHomedDown) {
621 singleHomedDown = expectSingleHomedDown;
622 log.info("{} downing of single homed hosts for lost uplinks",
623 singleHomedDown ? "Enabling" : "Disabling");
624 if (singleHomedDown && linkHandler != null) {
625 hostService.getHosts().forEach(host -> host.locations()
626 .forEach(loc -> {
627 if (interfaceService.isConfigured(loc)) {
628 linkHandler.checkUplinksForHost(loc);
629 }
630 }));
631 } else {
632 log.warn("Disabling singleHomedDown does not re-enable already "
633 + "downed ports for single-homed hosts");
634 }
635 }
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700636
637 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
638 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
639 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
640 respondToUnknownHosts = expectRespondToUnknownHosts;
641 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
642 }
Charles Chan57465d32018-07-19 14:55:31 -0700643
Charles Chanb67dfdd2018-07-24 16:40:35 -0700644 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
645 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
646 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
647 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
648 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan57465d32018-07-19 14:55:31 -0700649
Charles Chanb67dfdd2018-07-24 16:40:35 -0700650 if (routeDoubleTaggedHosts) {
Charles Chan57465d32018-07-19 14:55:31 -0700651 hostHandler.populateAllDoubleTaggedHost();
652 } else {
653 hostHandler.revokeAllDoubleTaggedHost();
654 }
655 }
Saurav Das09c2c4d2018-08-13 15:34:26 -0700656
657 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
658 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
659 if (defIntVlan != defaultInternalVlan) {
660 if (canUseVlanId(defIntVlan)) {
661 log.warn("Default internal vlan value changed from {} to {}.. "
662 + "re-programming filtering rules, but NOT any groups already "
663 + "created with the former value", defaultInternalVlan, defIntVlan);
664 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
665 defaultInternalVlan = defIntVlan;
666 routingRulePopulator
667 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
668 VlanId.vlanId((short) defIntVlan));
669 } else {
670 log.warn("Cannot change default internal vlan to unusable "
671 + "value {}", defIntVlan);
672 }
673 }
674
675 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
676 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
677 if (pwTxpVlan != pwTransportVlan) {
678 if (canUseVlanId(pwTxpVlan)) {
679 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
680 + "re-programming filtering rules, but NOT any groups already "
681 + "created with the former value", pwTransportVlan,
682 pwTxpVlan);
683 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
684 pwTransportVlan = pwTxpVlan;
685 routingRulePopulator
686 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
687 VlanId.vlanId((short) pwTxpVlan));
688 } else {
689 log.warn("Cannot change pseudowire transport vlan to unusable "
690 + "value {}", pwTxpVlan);
691 }
692 }
693
694 }
695
696 /**
697 * Returns true if given vlan id is not being used in the system currently,
698 * either as one of the default system wide vlans or as one of the
699 * configured interface vlans.
700 *
701 * @param vlanId given vlan id
702 * @return true if vlan is not currently in use
703 */
704 public boolean canUseVlanId(int vlanId) {
705 if (vlanId >= 4095 || vlanId <= 1) {
706 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
707 vlanId);
708 return false;
709 }
710
711 VlanId vid = VlanId.vlanId((short) vlanId);
712 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
713 log.warn("Vlan id {} value is already in use system-wide. "
714 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
715 getDefaultInternalVlan(), getPwTransportVlan());
716 return false;
717 }
718
719 if (interfaceService.inUse(vid)) {
720 log.warn("Vlan id {} value is already in use on a configured "
721 + "interface in the system", vlanId);
722 return false;
723 }
724 return true;
725 }
726
727 /**
728 * Returns the VlanId assigned internally by default to unconfigured ports.
729 *
730 * @return the default internal vlan id
731 */
732 public VlanId getDefaultInternalVlan() {
733 return VlanId.vlanId((short) defaultInternalVlan);
734 }
735
736 /**
737 * Returns the Vlan id used to transport pseudowire traffic across the
738 * network.
739 *
740 * @return the pseudowire transport vlan id
741 */
742 public VlanId getPwTransportVlan() {
743 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan47933752017-11-30 15:37:50 -0800744 }
745
sangho1e575652015-05-14 00:39:53 -0700746 @Override
747 public List<Tunnel> getTunnels() {
748 return tunnelHandler.getTunnels();
749 }
750
751 @Override
sangho71abe1b2015-06-29 14:58:47 -0700752 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
753 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700754 }
755
756 @Override
sangho71abe1b2015-06-29 14:58:47 -0700757 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700758 for (Policy policy: policyHandler.getPolicies()) {
759 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
760 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
761 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
762 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700763 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700764 }
765 }
766 }
sangho71abe1b2015-06-29 14:58:47 -0700767 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700768 }
769
770 @Override
sangho71abe1b2015-06-29 14:58:47 -0700771 public PolicyHandler.Result removePolicy(Policy policy) {
772 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700773 }
774
775 @Override
sangho71abe1b2015-06-29 14:58:47 -0700776 public PolicyHandler.Result createPolicy(Policy policy) {
777 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700778 }
779
780 @Override
781 public List<Policy> getPolicies() {
782 return policyHandler.getPolicies();
783 }
784
Saurav Das59232cf2016-04-27 18:35:50 -0700785 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700786 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
787 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700788 }
789
790 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800791 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700792 return l2TunnelHandler.getL2Tunnels();
793 }
794
795 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800796 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700797 return l2TunnelHandler.getL2Policies();
798 }
799
Saurav Das5a356042018-04-06 20:16:01 -0700800 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700801 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700802 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
803
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700804 // get both added and pending pseudowires
805 List<L2TunnelDescription> pseudowires = new ArrayList<>();
806 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
807 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700808 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700809
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700810 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
811
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700812 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
813 L2TunnelHandler.Result res;
814 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
815 res = addPseudowire(pw);
816 if (res != L2TunnelHandler.Result.SUCCESS) {
817 log.error("Pseudowire with id {} can not be instantiated !", res);
818 retRes = res;
819 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700820 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700821
822 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700823 }
824
825 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800826 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700827 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700828 }
829
830 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800831 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700832 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700833 }
834
835 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700836 public void rerouteNetwork() {
837 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700838 }
839
Charles Chanc81c45b2016-10-20 17:02:44 -0700840 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800841 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
842 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800843 deviceConfiguration.getRouters().forEach(device ->
844 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700845 return deviceSubnetMap;
846 }
847
Saurav Dasc88d4662017-05-15 15:34:25 -0700848
849 @Override
850 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
851 if (defaultRoutingHandler != null) {
852 return defaultRoutingHandler.getCurrentEmcpSpgMap();
853 } else {
854 return null;
855 }
856 }
857
858 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700859 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
860 if (dsNextObjStore != null) {
861 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700862 } else {
863 return ImmutableMap.of();
864 }
865 }
866
Saurav Dasceccf242017-08-03 18:30:35 -0700867 @Override
868 public void verifyGroups(DeviceId id) {
869 DefaultGroupHandler gh = groupHandlerMap.get(id);
870 if (gh != null) {
871 gh.triggerBucketCorrector();
872 }
873 }
874
Saurav Dasc568c342018-01-25 09:49:01 -0800875 @Override
876 public ImmutableMap<Link, Boolean> getSeenLinks() {
877 return linkHandler.getSeenLinks();
878 }
879
880 @Override
881 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
882 return linkHandler.getDownedPorts();
883 }
884
Pier Luigib29144d2018-01-15 18:06:43 +0100885 @Override
886 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
887 return mcastHandler.getMcastNextIds(mcastIp);
888 }
889
890 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100891 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100892 return mcastHandler.getMcastRoles(mcastIp);
893 }
894
895 @Override
Pier3e793752018-04-19 16:47:06 +0200896 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
897 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
898 }
899
900 @Override
Pier Luigib29144d2018-01-15 18:06:43 +0100901 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
902 return mcastHandler.getMcastPaths(mcastIp);
903 }
904
Pier96f63cb2018-04-17 16:29:56 +0200905 @Override
Pierb1fe7382018-04-17 17:25:22 +0200906 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
907 ConnectPoint sourcecp) {
908 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
909 }
910
911 @Override
Pier96f63cb2018-04-17 16:29:56 +0200912 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
913 return mcastHandler.getMcastLeaders(mcastIp);
914 }
915
Charles Chan8bc75ee2018-04-17 18:56:53 -0700916 @Override
917 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
918 return defaultRoutingHandler == null ? ImmutableMap.of() :
919 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
920 }
921
922 @Override
923 public Map<DeviceId, Boolean> getShouldProgramCache() {
924 return defaultRoutingHandler == null ? ImmutableMap.of() :
925 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
926 }
927
Charles Chanc7b3c452018-06-19 20:31:57 -0700928 @Override
Ray Milkeye4afdb52017-04-05 09:42:04 -0700929 public ApplicationId appId() {
930 return appId;
931 }
932
933 /**
934 * Returns the device configuration.
935 *
936 * @return device configuration
937 */
938 public DeviceConfiguration deviceConfiguration() {
939 return deviceConfiguration;
940 }
941
942 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700943 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700944 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700945 *
946 * @return next objective ID store
947 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700948 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
949 dsNextObjStore() {
950 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700951 }
952
953 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700954 * Per device next objective ID store with (device id + vlanid) as key.
955 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700956 *
957 * @return vlan next object store
958 */
959 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
960 return vlanNextObjStore;
961 }
962
963 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700964 * Per device next objective ID store with (device id + port + treatment + meta) as key.
965 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700966 *
967 * @return port next object store.
968 */
969 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
970 return portNextObjStore;
971 }
972
973 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700974 * Per port dummy VLAN ID store with (connect point + ip address) as key.
975 * Used to keep track on dummy VLAN ID allocation.
976 *
977 * @return dummy vlan id store.
978 */
979 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
980 return dummyVlanIdStore;
981 }
982
983 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700984 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
985 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700986 *
987 * @return MPLS-ECMP value
988 */
989 public boolean getMplsEcmp() {
990 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
991 .getConfig(this.appId, SegmentRoutingAppConfig.class);
992 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
993 }
994
995 /**
sanghof9d0bf12015-05-19 11:57:42 -0700996 * Returns the tunnel object with the tunnel ID.
997 *
998 * @param tunnelId Tunnel ID
999 * @return Tunnel reference
1000 */
sangho1e575652015-05-14 00:39:53 -07001001 public Tunnel getTunnel(String tunnelId) {
1002 return tunnelHandler.getTunnel(tunnelId);
1003 }
1004
Charles Chanc7b3c452018-06-19 20:31:57 -07001005 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +01001006 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan971d7ba2018-05-01 11:50:20 -07001007 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1008 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -07001009 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1010 }
1011
Charles Chanc7b3c452018-06-19 20:31:57 -07001012 @Override
1013 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001014 SegmentRoutingDeviceConfig deviceConfig =
1015 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1016 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1017 }
Charles Chanc7b3c452018-06-19 20:31:57 -07001018
1019 @Override
Saurav Das9a554292018-04-27 18:42:30 -07001020 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001021 SegmentRoutingDeviceConfig deviceConfig =
1022 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1023 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1024 }
1025
1026 /**
Charles Chan9640c812017-08-23 13:55:39 -07001027 * Returns locations of given resolved route.
1028 *
1029 * @param resolvedRoute resolved route
1030 * @return locations of nexthop. Might be empty if next hop is not found
1031 */
1032 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1033 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1034 return Optional.ofNullable(hostService.getHost(hostId))
1035 .map(Host::locations).orElse(Sets.newHashSet())
1036 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1037 }
1038
1039 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -08001040 * Returns vlan port map of given device.
1041 *
1042 * @param deviceId device id
1043 * @return vlan-port multimap
1044 */
1045 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1046 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1047
1048 interfaceService.getInterfaces().stream()
1049 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1050 .forEach(intf -> {
1051 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -07001052 intf.vlanTagged().forEach(vlanTagged ->
1053 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1054 );
Charles Chan7ffd81f2017-02-08 15:52:08 -08001055 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1056 });
1057 vlanPortMap.removeAll(VlanId.NONE);
1058
1059 return vlanPortMap;
1060 }
1061
1062 /**
Charles Chan59cc16d2017-02-02 16:20:42 -08001063 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -08001064 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -07001065 *
1066 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -08001067 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -08001068 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -07001069 */
Charles Chan65238242017-06-22 18:03:14 -07001070 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -07001071 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -08001072 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1073 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001074 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -08001075 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -08001076 + "device {} not found", deviceId);
1077 return -1;
1078 }
1079 }
1080
1081 /**
1082 * Returns the next objective ID for the given portNumber, given the treatment.
1083 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -07001084 * would result in different objectives. If the next object does not exist,
1085 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -08001086 *
1087 * @param deviceId Device ID
1088 * @param portNum port number on device for which NextObjective is queried
1089 * @param treatment the actions to apply on the packets (should include outport)
1090 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -07001091 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -07001092 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -08001093 */
1094 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1095 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -07001096 TrafficSelector meta,
1097 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -08001098 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1099 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -07001100 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -08001101 } else {
Charles Chane849c192016-01-11 18:28:54 -08001102 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1103 + " not found", deviceId);
1104 return -1;
1105 }
1106 }
1107
Saurav Dasc88d4662017-05-15 15:34:25 -07001108 /**
1109 * Returns the group handler object for the specified device id.
1110 *
1111 * @param devId the device identifier
1112 * @return the groupHandler object for the device id, or null if not found
1113 */
Charles Chan65238242017-06-22 18:03:14 -07001114 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001115 return groupHandlerMap.get(devId);
1116 }
1117
1118 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001119 * Returns the default routing handler object.
1120 *
1121 * @return the default routing handler object
1122 */
1123 public DefaultRoutingHandler getRoutingHandler() {
1124 return defaultRoutingHandler;
1125 }
1126
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001127 /**
1128 * Returns new dummy VLAN ID.
1129 * Dummy VLAN ID should be unique in each connect point.
1130 *
1131 * @param cp connect point
1132 * @param ipAddress IP address
1133 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1134 */
1135 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1136 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1137 dummyVlanIdStore.entrySet().stream().filter(entry ->
1138 (entry.getKey()).connectPoint().equals(cp))
1139 .map(Map.Entry::getValue)
1140 .collect(Collectors.toSet()));
1141
1142 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1143 i -> VlanId.vlanId((short) (i & 0xFFFF))
1144 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1145
1146 if (!dummyVlanId.equals(VlanId.NONE)) {
1147 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1148 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1149 } else {
1150 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1151 }
1152 return dummyVlanId;
1153 }
1154
1155
sanghob35a6192015-04-01 13:05:26 -07001156 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001157 @Override
1158 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -07001159 packetExecutor.execute(() -> processPacketInternal(context));
1160 }
sanghob35a6192015-04-01 13:05:26 -07001161
Charles Chan07f15f22018-05-08 21:35:50 -07001162 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001163 if (context.isHandled()) {
1164 return;
1165 }
1166
1167 InboundPacket pkt = context.inPacket();
1168 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001169
1170 if (ethernet == null) {
1171 return;
1172 }
1173
Saurav Das7bcbe702017-06-13 15:35:54 -07001174 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1175 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001176 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001177 log.warn("Received unexpected ARP packet on {}",
1178 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001179 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001180 return;
sanghob35a6192015-04-01 13:05:26 -07001181 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001182 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1183 //ipHandler.addToPacketBuffer(ipv4Packet);
1184 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1185 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001186 } else {
Charles Chan50035632017-01-13 17:20:44 -08001187 // NOTE: We don't support IP learning at this moment so this
1188 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001189 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001190 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001191 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1192 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001193 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001194 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001195 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1196 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1197 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1198 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1199 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1200 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001201 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001202 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001203 }
1204 } else {
1205 // NOTE: We don't support IP learning at this moment so this
1206 // is not necessary. Also it causes duplication of DHCPv6 packets.
1207 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1208 }
sanghob35a6192015-04-01 13:05:26 -07001209 }
1210 }
1211 }
1212
sanghob35a6192015-04-01 13:05:26 -07001213 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001214 private Event event;
1215
1216 InternalEventHandler(Event event) {
1217 this.event = event;
1218 }
1219
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001220 @Override
sanghob35a6192015-04-01 13:05:26 -07001221 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001222 try {
1223 // TODO We should also change SR routing and PW to listen to TopologyEvents
1224 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1225 event.type() == LinkEvent.Type.LINK_UPDATED) {
1226 linkHandler.processLinkAdded((Link) event.subject());
1227 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1228 linkHandler.processLinkRemoved((Link) event.subject());
1229 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1230 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1231 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1232 DeviceId deviceId = ((Device) event.subject()).id();
1233 if (deviceService.isAvailable(deviceId)) {
1234 log.info("** DEVICE UP Processing device event {} "
1235 + "for available device {}",
1236 event.type(), ((Device) event.subject()).id());
1237 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001238 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001239 log.info(" ** DEVICE DOWN Processing device event {}"
1240 + " for unavailable device {}",
1241 event.type(), ((Device) event.subject()).id());
1242 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001243 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001244 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1245 // typically these calls come when device is added first time
1246 // so port filtering rules are handled at the device_added event.
1247 // port added calls represent all ports on the device,
1248 // enabled or not.
1249 log.trace("** PORT ADDED {}/{} -> {}",
1250 ((DeviceEvent) event).subject().id(),
1251 ((DeviceEvent) event).port().number(),
1252 event.type());
1253 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1254 // these calls happen for every subsequent event
1255 // ports enabled, disabled, switch goes away, comes back
1256 log.info("** PORT UPDATED {}/{} -> {}",
1257 event.subject(),
1258 ((DeviceEvent) event).port(),
1259 event.type());
Saurav Das9a554292018-04-27 18:42:30 -07001260 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001261 ((DeviceEvent) event).port());
1262 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1263 // Process topology event, needed for all modules relying on
1264 // topology service for path computation
1265 TopologyEvent topologyEvent = (TopologyEvent) event;
1266 log.info("Processing topology event {}, topology age {}, reasons {}",
1267 event.type(), topologyEvent.subject().time(),
1268 topologyEvent.reasons().size());
1269 topologyHandler.processTopologyChange(topologyEvent.reasons());
1270 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1271 hostHandler.processHostAddedEvent((HostEvent) event);
1272 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1273 hostHandler.processHostMovedEvent((HostEvent) event);
1274 routeHandler.processHostMovedEvent((HostEvent) event);
1275 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1276 hostHandler.processHostRemovedEvent((HostEvent) event);
1277 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1278 hostHandler.processHostUpdatedEvent((HostEvent) event);
1279 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1280 routeHandler.processRouteAdded((RouteEvent) event);
1281 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1282 routeHandler.processRouteUpdated((RouteEvent) event);
1283 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1284 routeHandler.processRouteRemoved((RouteEvent) event);
1285 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1286 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1287 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1288 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1289 event.type() == McastEvent.Type.SINKS_ADDED ||
1290 event.type() == McastEvent.Type.SINKS_REMOVED ||
1291 event.type() == McastEvent.Type.ROUTE_ADDED ||
1292 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1293 mcastHandler.processMcastEvent((McastEvent) event);
1294 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1295 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1296 Class configClass = netcfgEvent.configClass();
1297 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1298 appCfgHandler.processAppConfigAdded(netcfgEvent);
1299 log.info("App config event .. configuring network");
1300 cfgListener.configureNetwork();
1301 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1302 log.info("Segment Routing Device Config added for {}", event.subject());
1303 cfgListener.configureNetwork();
1304 } else if (configClass.equals(XConnectConfig.class)) {
1305 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1306 } else if (configClass.equals(InterfaceConfig.class)) {
1307 log.info("Interface Config added for {}", event.subject());
1308 cfgListener.configureNetwork();
1309 } else {
1310 log.error("Unhandled config class: {}", configClass);
1311 }
1312 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1313 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1314 Class configClass = netcfgEvent.configClass();
1315 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1316 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1317 log.info("App config event .. configuring network");
1318 cfgListener.configureNetwork();
1319 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1320 log.info("Segment Routing Device Config updated for {}", event.subject());
1321 createOrUpdateDeviceConfiguration();
1322 } else if (configClass.equals(XConnectConfig.class)) {
1323 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1324 } else if (configClass.equals(InterfaceConfig.class)) {
1325 log.info("Interface Config updated for {}", event.subject());
1326 createOrUpdateDeviceConfiguration();
1327 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1328 (InterfaceConfig) netcfgEvent.prevConfig().get());
1329 } else {
1330 log.error("Unhandled config class: {}", configClass);
1331 }
1332 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1333 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1334 Class configClass = netcfgEvent.configClass();
1335 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1336 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1337 log.info("App config event .. configuring network");
1338 cfgListener.configureNetwork();
1339 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1340 // TODO Handle sr device config removal
1341 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1342 } else if (configClass.equals(XConnectConfig.class)) {
1343 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1344 } else if (configClass.equals(InterfaceConfig.class)) {
1345 // TODO Handle interface removal
1346 log.info("InterfaceConfig removal is not handled in current implementation");
1347 } else {
1348 log.error("Unhandled config class: {}", configClass);
1349 }
Saurav Das201762d2018-04-21 17:19:48 -07001350 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1351 MastershipEvent me = (MastershipEvent) event;
1352 DeviceId deviceId = me.subject();
1353 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1354 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1355 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1356 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1357 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1358 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001359 } else {
1360 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001361 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001362 } catch (Exception e) {
1363 log.error("SegmentRouting event handler thread thrown an exception: {}",
1364 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001365 }
sanghob35a6192015-04-01 13:05:26 -07001366 }
1367 }
1368
Saurav Das45f48152018-01-18 12:07:33 -08001369 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001370 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001371
1372 // NOTE: Punt ARP/NDP even when the device is not configured.
1373 // Host learning without network config is required for CORD config generator.
1374 routingRulePopulator.populateIpPunts(device.id());
1375 routingRulePopulator.populateArpNdpPunts(device.id());
1376
Charles Chan0b4e6182015-11-03 10:42:14 -08001377 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001378 log.warn("Device configuration unavailable. Device {} will be "
1379 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001380 return;
1381 }
Charles Chan2199c302016-04-23 17:36:10 -07001382 processDeviceAddedInternal(device.id());
1383 }
1384
1385 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001386 // Irrespective of whether the local is a MASTER or not for this device,
1387 // we need to create a SR-group-handler instance. This is because in a
1388 // multi-instance setup, any instance can initiate forwarding/next-objectives
1389 // for any switch (even if this instance is a SLAVE or not even connected
1390 // to the switch). To handle this, a default-group-handler instance is necessary
1391 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001392 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1393 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001394 DefaultGroupHandler groupHandler;
1395 try {
1396 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001397 createGroupHandler(deviceId,
1398 appId,
1399 deviceConfiguration,
1400 linkService,
1401 flowObjectiveService,
1402 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001403 } catch (DeviceConfigNotFoundException e) {
1404 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1405 return;
1406 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001407 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001408 deviceId);
1409 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001410 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001411
Charles Chan2199c302016-04-23 17:36:10 -07001412 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001413 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001414 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001415 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001416 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001417 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001418 }
Charles Chan5270ed02016-01-30 23:22:37 -08001419
Charles Chan03a73e02016-10-24 14:52:01 -07001420 appCfgHandler.init(deviceId);
Charles Chan94549652018-04-29 18:11:37 -07001421 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1422 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001423 }
1424
Saurav Das80980c72016-03-23 11:22:49 -07001425 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001426 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001427 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001428 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001429 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001430 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001431 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001432 portNextObjStore.entrySet().stream()
1433 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001434 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001435 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001436
Saurav Dasceccf242017-08-03 18:30:35 -07001437 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1438 if (gh != null) {
1439 gh.shutdown();
1440 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001441 // Note that a switch going down is associated with all of its links
1442 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001443 // while the link-downs are ignored. We cannot rely on the ordering of
1444 // events - i.e we cannot expect all link-downs to come before the
1445 // switch down - so we purge all seen-links for the switch before
1446 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001447 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001448 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001449 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001450 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001451
1452 // Cleanup all internal groupHandler stores for this device. Should be
1453 // done after all rerouting or rehashing has been completed
1454 groupHandlerMap.entrySet()
1455 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001456 }
1457
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001458 /**
1459 * Purge the destinationSet nextObjective store of entries with this device
1460 * as key. Erases app-level knowledge of hashed groups in this device.
1461 *
1462 * @param devId the device identifier
1463 */
Saurav Das201762d2018-04-21 17:19:48 -07001464 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001465 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das201762d2018-04-21 17:19:48 -07001466 dsNextObjStore.entrySet().stream()
1467 .filter(entry -> entry.getKey().deviceId().equals(devId))
1468 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1469 }
1470
Saurav Das9a554292018-04-27 18:42:30 -07001471 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001472 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1473 log.warn("Device configuration uploading. Not handling port event for"
1474 + "dev: {} port: {}", device.id(), port.number());
1475 return;
1476 }
Saurav Das018605f2017-02-18 14:05:44 -08001477
Saurav Das9a554292018-04-27 18:42:30 -07001478 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1479 lastEdgePortEvent = Instant.now();
1480 }
1481
Saurav Das018605f2017-02-18 14:05:44 -08001482 if (!mastershipService.isLocalMaster(device.id())) {
1483 log.debug("Not master for dev:{} .. not handling port updated event"
1484 + "for port {}", device.id(), port.number());
1485 return;
1486 }
Saurav Das9a554292018-04-27 18:42:30 -07001487 processPortUpdated(device.id(), port);
1488 }
Saurav Das018605f2017-02-18 14:05:44 -08001489
Saurav Das9a554292018-04-27 18:42:30 -07001490 /**
1491 * Adds or remove filtering rules for the given switchport. If switchport is
1492 * an edge facing port, additionally handles host probing and broadcast
1493 * rules. Must be called by local master of device.
1494 *
1495 * @param deviceId the device identifier
1496 * @param port the port to update
1497 */
1498 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001499 // first we handle filtering rules associated with the port
1500 if (port.isEnabled()) {
1501 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das9a554292018-04-27 18:42:30 -07001502 deviceId, port.number());
1503 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001504 } else {
1505 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das9a554292018-04-27 18:42:30 -07001506 deviceId, port.number());
1507 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001508 }
Saurav Das1a129a02016-11-18 15:21:57 -08001509
1510 // portUpdated calls are for ports that have gone down or up. For switch
1511 // to switch ports, link-events should take care of any re-routing or
1512 // group editing necessary for port up/down. Here we only process edge ports
1513 // that are already configured.
Saurav Das9a554292018-04-27 18:42:30 -07001514 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan971d7ba2018-05-01 11:50:20 -07001515 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1516 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1517 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001518
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001519 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001520 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das9a554292018-04-27 18:42:30 -07001521 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001522 return;
1523 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001524 if (untaggedVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001525 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001526 }
1527 if (nativeVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001528 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001529 }
1530 if (!taggedVlans.isEmpty()) {
Saurav Das9a554292018-04-27 18:42:30 -07001531 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001532 }
Saurav Das1a129a02016-11-18 15:21:57 -08001533 }
1534
Saurav Das9a554292018-04-27 18:42:30 -07001535 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001536 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001537 boolean portUp = port.isEnabled();
1538 if (portUp) {
Saurav Das9a554292018-04-27 18:42:30 -07001539 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001540 port.number(), vlanId);
Charles Chan94549652018-04-29 18:11:37 -07001541 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001542 } else {
Saurav Das9a554292018-04-27 18:42:30 -07001543 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001544 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001545 }
1546
Saurav Das9a554292018-04-27 18:42:30 -07001547 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001548 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001549 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001550 } else {
1551 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das9a554292018-04-27 18:42:30 -07001552 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001553 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001554 }
1555 }
sangho1e575652015-05-14 00:39:53 -07001556
Charles Chan27fe1a52017-10-20 16:06:55 -07001557 private void createOrUpdateDeviceConfiguration() {
1558 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001559 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001560 deviceConfiguration = new DeviceConfiguration(this);
1561 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001562 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001563 deviceConfiguration.updateConfig();
1564 }
1565 }
1566
Charles Chan50bb6ef2018-04-18 18:41:05 -07001567 private void createOrUpdateDefaultRoutingHandler() {
1568 if (defaultRoutingHandler == null) {
1569 log.info("Creating new DefaultRoutingHandler");
1570 defaultRoutingHandler = new DefaultRoutingHandler(this);
1571 } else {
1572 log.info("Updating DefaultRoutingHandler");
1573 defaultRoutingHandler.update(this);
1574 }
1575 }
1576
Pier Ventre10bd8d12016-11-26 21:05:22 -08001577 /**
1578 * Registers the given connect point with the NRS, this is necessary
1579 * to receive the NDP and ARP packets from the NRS.
1580 *
1581 * @param portToRegister connect point to register
1582 */
1583 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001584 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001585 portToRegister,
1586 neighbourHandler,
1587 appId
1588 );
1589 }
1590
Charles Chand6832882015-10-05 17:50:33 -07001591 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001592 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001593 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001594
Charles Chane849c192016-01-11 18:28:54 -08001595 /**
1596 * Constructs the internal network config listener.
1597 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001598 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001599 */
Charles Chan65238242017-06-22 18:03:14 -07001600 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001601 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001602 }
1603
Charles Chane849c192016-01-11 18:28:54 -08001604 /**
1605 * Reads network config and initializes related data structure accordingly.
1606 */
Charles Chan47933752017-11-30 15:37:50 -08001607 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001608 log.info("Configuring network ...");
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001609
1610 // Setting handling of network configuration events completable future
1611 // The completable future is needed because of the async behaviour of the configureNetwork,
1612 // listener registration and event arrival
1613 // Enables us to buffer the events and execute them when the configure network is done.
1614 networkConfigCompletion = new CompletableFuture<>();
1615
1616 // add a small delay to absorb multiple network config added notifications
1617 if (!programmingScheduled.get()) {
1618 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1619 programmingScheduled.set(true);
1620 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1621 }
1622
Charles Chan27fe1a52017-10-20 16:06:55 -07001623 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001624
Charles Chan2c15aca2016-11-09 20:51:44 -08001625 arpHandler = new ArpHandler(srManager);
1626 icmpHandler = new IcmpHandler(srManager);
1627 ipHandler = new IpHandler(srManager);
1628 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chan50bb6ef2018-04-18 18:41:05 -07001629 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001630
1631 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1632 groupHandlerMap, tunnelStore);
1633 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1634 flowObjectiveService,
1635 tunnelHandler, policyStore);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001636 networkConfigCompletion.complete(true);
1637
Charles Chan2199c302016-04-23 17:36:10 -07001638 mcastHandler.init();
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001639
Charles Chan4636be02015-10-07 14:21:45 -07001640 }
1641
Charles Chand6832882015-10-05 17:50:33 -07001642 @Override
1643 public void event(NetworkConfigEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001644 if (mainEventExecutor == null) {
1645 return;
1646 }
Charles Chan7a888e82018-03-21 16:57:47 -07001647 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1648 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1649 switch (event.type()) {
1650 case CONFIG_ADDED:
1651 case CONFIG_UPDATED:
1652 case CONFIG_REMOVED:
1653 log.trace("Schedule Network Config event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001654 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1655 mainEventExecutor.execute(new InternalEventHandler(event));
1656 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001657 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001658 }
Charles Chan7a888e82018-03-21 16:57:47 -07001659 break;
1660 default:
1661 break;
Charles Chand6832882015-10-05 17:50:33 -07001662 }
1663 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001664
Charles Chan50443e82018-01-03 16:26:32 -08001665 @Override
1666 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001667 if (event.type() == CONFIG_REGISTERED ||
1668 event.type() == CONFIG_UNREGISTERED) {
1669 log.debug("Ignore event {} due to type mismatch", event);
1670 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001671 }
Saurav Dase7f51012018-02-09 17:26:45 -08001672
1673 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1674 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1675 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001676 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001677 log.debug("Ignore event {} due to class mismatch", event);
1678 return false;
1679 }
1680
1681 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001682 }
1683
Saurav Das7bcbe702017-06-13 15:35:54 -07001684 private final class ConfigChange implements Runnable {
1685 @Override
1686 public void run() {
1687 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001688 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001689 for (Device device : deviceService.getDevices()) {
1690 processDeviceAdded(device);
1691 }
1692 defaultRoutingHandler.startPopulationProcess();
1693 }
1694 }
Charles Chand6832882015-10-05 17:50:33 -07001695 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001696
Charles Chan7a888e82018-03-21 16:57:47 -07001697 private class InternalLinkListener implements LinkListener {
1698 @Override
1699 public void event(LinkEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001700 if (mainEventExecutor == null) {
1701 return;
1702 }
Charles Chan7a888e82018-03-21 16:57:47 -07001703 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1704 event.type() == LinkEvent.Type.LINK_UPDATED ||
1705 event.type() == LinkEvent.Type.LINK_REMOVED) {
1706 log.trace("Schedule Link event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001707 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1708 mainEventExecutor.execute(new InternalEventHandler(event));
1709 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001710 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001711 }
Charles Chan7a888e82018-03-21 16:57:47 -07001712 }
1713 }
1714 }
1715
1716 private class InternalDeviceListener implements DeviceListener {
1717 @Override
1718 public void event(DeviceEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001719 if (mainEventExecutor == null) {
1720 return;
1721 }
Charles Chan7a888e82018-03-21 16:57:47 -07001722 switch (event.type()) {
1723 case DEVICE_ADDED:
1724 case PORT_UPDATED:
1725 case PORT_ADDED:
1726 case DEVICE_UPDATED:
1727 case DEVICE_AVAILABILITY_CHANGED:
1728 log.trace("Schedule Device event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001729 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1730 mainEventExecutor.execute(new InternalEventHandler(event));
1731 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001732 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001733 }
Charles Chan7a888e82018-03-21 16:57:47 -07001734 break;
1735 default:
1736 }
1737 }
1738 }
1739
1740 private class InternalTopologyListener implements TopologyListener {
1741 @Override
1742 public void event(TopologyEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001743 if (mainEventExecutor == null) {
1744 return;
1745 }
Charles Chan7a888e82018-03-21 16:57:47 -07001746 switch (event.type()) {
1747 case TOPOLOGY_CHANGED:
1748 log.trace("Schedule Topology event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001749 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1750 mainEventExecutor.execute(new InternalEventHandler(event));
1751 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001752 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001753 }
Charles Chan7a888e82018-03-21 16:57:47 -07001754 break;
1755 default:
1756 }
1757 }
1758 }
1759
Charles Chan68aa62d2015-11-09 16:37:23 -08001760 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001761 @Override
1762 public void event(HostEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001763 if (hostEventExecutor == null) {
1764 return;
1765 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001766 switch (event.type()) {
1767 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001768 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001769 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001770 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001771 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001772 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001773 break;
1774 default:
1775 log.warn("Unsupported host event type: {}", event.type());
1776 break;
1777 }
1778 }
1779 }
1780
Charles Chand55e84d2016-03-30 17:54:24 -07001781 private class InternalMcastListener implements McastListener {
1782 @Override
1783 public void event(McastEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001784 if (mcastEventExecutor == null) {
1785 return;
1786 }
Charles Chand55e84d2016-03-30 17:54:24 -07001787 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001788 case SOURCES_ADDED:
1789 case SOURCES_REMOVED:
1790 case SINKS_ADDED:
1791 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001792 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001793 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001794 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001795 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001796 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001797 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001798 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001799 break;
1800 }
1801 }
1802 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001803
Charles Chan03a73e02016-10-24 14:52:01 -07001804 private class InternalRouteEventListener implements RouteListener {
1805 @Override
1806 public void event(RouteEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001807 if (routeEventExecutor == null) {
1808 return;
1809 }
Charles Chan03a73e02016-10-24 14:52:01 -07001810 switch (event.type()) {
1811 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001812 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001813 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001814 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001815 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001816 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001817 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001818 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001819 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001820 break;
1821 }
1822 }
1823 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001824
Charles Chan50bb6ef2018-04-18 18:41:05 -07001825 private class InternalMastershipListener implements MastershipListener {
1826 @Override
1827 public void event(MastershipEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001828 if (mainEventExecutor == null) {
1829 return;
1830 }
Charles Chan50bb6ef2018-04-18 18:41:05 -07001831 switch (event.type()) {
Saurav Das201762d2018-04-21 17:19:48 -07001832 case MASTER_CHANGED:
1833 log.debug("Mastership event: {}/{}", event.subject(),
1834 event.roleInfo());
1835 mainEventExecutor.execute(new InternalEventHandler(event));
1836 break;
1837 case BACKUPS_CHANGED:
1838 case SUSPENDED:
1839 default:
1840 log.debug("Mastership event type {} not handled", event.type());
1841 break;
Charles Chan50bb6ef2018-04-18 18:41:05 -07001842 }
1843 }
1844 }
1845
Saurav Das201762d2018-04-21 17:19:48 -07001846 class InternalClusterListener implements ClusterEventListener {
1847 private Instant lastClusterEvent = Instant.EPOCH;
1848
1849 long timeSinceLastClusterEvent() {
1850 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1851 }
1852
1853 @Override
1854 public void event(ClusterEvent event) {
1855 switch (event.type()) {
1856 case INSTANCE_ACTIVATED:
1857 case INSTANCE_ADDED:
1858 case INSTANCE_READY:
1859 log.debug("Cluster event {} ignored", event.type());
1860 break;
1861 case INSTANCE_DEACTIVATED:
1862 case INSTANCE_REMOVED:
1863 log.info("** Cluster event {}", event.type());
1864 lastClusterEvent = Instant.now();
1865 break;
1866 default:
1867 break;
1868 }
1869
1870 }
1871
1872 }
1873
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001874 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1875 try {
1876 Set<Interface> intfs = conf.getInterfaces();
1877 Set<Interface> prevIntfs = prevConf.getInterfaces();
1878
1879 // Now we only handle one interface config at each port.
1880 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1881 log.warn("Interface update aborted - one at a time is allowed, " +
1882 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1883 return;
1884 }
1885
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001886 //The system is in an incoherent state, abort
1887 if (defaultRoutingHandler == null) {
1888 log.warn("Interface update aborted, defaultRoutingHandler is null");
1889 return;
1890 }
1891
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001892 Interface intf = intfs.stream().findFirst().get();
1893 Interface prevIntf = prevIntfs.stream().findFirst().get();
1894
1895 DeviceId deviceId = intf.connectPoint().deviceId();
1896 PortNumber portNum = intf.connectPoint().port();
1897
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001898 removeSubnetConfig(prevIntf.connectPoint(),
1899 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1900 new HashSet<>(intf.ipAddressesList())));
1901
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001902 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1903 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1904 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1905 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1906 // Update filtering objective and L2IG group bucket
1907 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1908 } else {
1909 // RemoveVlanNative
1910 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1911 }
1912 }
1913
1914 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1915 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1916 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1917 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1918 // Update filtering objective and L2IG group bucket
1919 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1920 } else {
1921 // RemoveVlanUntagged
1922 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1923 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001924 }
1925
1926 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1927 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001928 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1929 .filter(i -> !intf.vlanUntagged().equals(i))
1930 .filter(i -> !intf.vlanNative().equals(i))
1931 .forEach(vlanId -> updateVlanConfigInternal(
1932 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001933 }
1934
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001935 if (!intf.vlanNative().equals(VlanId.NONE)
1936 && !prevIntf.vlanNative().equals(intf.vlanNative())
1937 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1938 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1939 // Update filtering objective and L2IG group bucket
1940 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1941 } else {
1942 // AddVlanNative
1943 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1944 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001945 }
1946
1947 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1948 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001949 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1950 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1951 .filter(i -> !prevIntf.vlanNative().equals(i))
1952 .forEach(vlanId -> updateVlanConfigInternal(
1953 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001954 );
1955 }
1956
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001957 if (!intf.vlanUntagged().equals(VlanId.NONE)
1958 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1959 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1960 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1961 // Update filtering objective and L2IG group bucket
1962 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1963 } else {
1964 // AddVlanUntagged
1965 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1966 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001967 }
1968 addSubnetConfig(prevIntf.connectPoint(),
1969 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1970 new HashSet<>(prevIntf.ipAddressesList())));
1971 } catch (ConfigException e) {
1972 log.error("Error in configuration");
1973 }
1974 }
1975
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001976 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1977 VlanId vlanId, boolean pushVlan) {
1978 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1979 if (grpHandler == null) {
1980 log.warn("Failed to retrieve group handler for device {}", deviceId);
1981 return;
1982 }
1983
1984 // Update filtering objective for a single port
1985 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1986 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1987
1988 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1989 // Update L2IG bucket of the port
1990 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1991 } else {
1992 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1993 }
1994 }
1995
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001996 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1997 VlanId vlanId, boolean pushVlan, boolean install) {
1998 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1999 if (grpHandler == null) {
2000 log.warn("Failed to retrieve group handler for device {}", deviceId);
2001 return;
2002 }
2003
2004 // Update filtering objective for a single port
2005 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2006
2007 // Update filtering objective for multicast ingress port
2008 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2009
2010 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2011
2012 if (nextId != -1 && !install) {
2013 // Update next objective for a single port as an output port
2014 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002015 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002016 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan94549652018-04-29 18:11:37 -07002017 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2018 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002019 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2020 // only if there is no port configured on that VLAN ID
2021 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2022 // Remove broadcast forwarding rule for the VLAN
2023 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2024 // Remove L2FG for VLAN
2025 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2026 } else {
2027 // Remove L2IG of the port
2028 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2029 }
2030 } else if (install) {
2031 if (nextId != -1) {
2032 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002033 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002034 } else {
2035 // Create L2FG for VLAN
2036 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2037 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2038 }
Charles Chan94549652018-04-29 18:11:37 -07002039 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2040 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002041 } else {
2042 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2043 }
2044 }
2045
2046 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2047 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2048 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2049
2050 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2051 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2052 .filter(intf -> !intf.connectPoint().equals(cp))
2053 .flatMap(intf -> intf.ipAddressesList().stream())
2054 .collect(Collectors.toSet());
2055 // 1. Partial subnet population
2056 // Remove routing rules for removed subnet from previous configuration,
2057 // which does not also exist in other interfaces in the same device
2058 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2059 .map(InterfaceIpAddress::subnetAddress)
2060 .collect(Collectors.toSet());
2061
2062 defaultRoutingHandler.revokeSubnet(
2063 ipPrefixSet.stream()
2064 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2065 .collect(Collectors.toSet()));
2066
2067 // 2. Interface IP punts
2068 // Remove IP punts for old Intf address
2069 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2070 .map(InterfaceIpAddress::ipAddress)
2071 .collect(Collectors.toSet());
2072 ipAddressSet.stream()
2073 .map(InterfaceIpAddress::ipAddress)
2074 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2075 .forEach(interfaceIpAddress ->
2076 routingRulePopulator.revokeSingleIpPunts(
2077 cp.deviceId(), interfaceIpAddress));
2078
2079 // 3. Host unicast routing rule
2080 // Remove unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002081 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002082 }
2083
2084 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2085 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2086 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2087
2088 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2089 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2090 .filter(intf -> !intf.connectPoint().equals(cp))
2091 .flatMap(intf -> intf.ipAddressesList().stream())
2092 .collect(Collectors.toSet());
2093 // 1. Partial subnet population
2094 // Add routing rules for newly added subnet, which does not also exist in
2095 // other interfaces in the same device
2096 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2097 .map(InterfaceIpAddress::subnetAddress)
2098 .collect(Collectors.toSet());
2099
2100 defaultRoutingHandler.populateSubnet(
2101 Collections.singleton(cp),
2102 ipPrefixSet.stream()
2103 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2104 .collect(Collectors.toSet()));
2105
2106 // 2. Interface IP punts
2107 // Add IP punts for new Intf address
2108 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2109 .map(InterfaceIpAddress::ipAddress)
2110 .collect(Collectors.toSet());
2111 ipAddressSet.stream()
2112 .map(InterfaceIpAddress::ipAddress)
2113 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2114 .forEach(interfaceIpAddress ->
2115 routingRulePopulator.populateSingleIpPunts(
2116 cp.deviceId(), interfaceIpAddress));
2117
2118 // 3. Host unicast routing rule
2119 // Add unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002120 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002121 }
sanghob35a6192015-04-01 13:05:26 -07002122}