blob: bd5c8c4a73c5a69ee70088999e11e5971bf13ffe [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");
Charles Chan47933752017-11-30 15:37:50 -0800475 compCfgService.registerProperties(getClass());
476 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700477
Charles Chanb8e10c82015-10-14 11:24:40 -0700478 processor = new InternalPacketProcessor();
479 linkListener = new InternalLinkListener();
480 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700481 appCfgHandler = new AppConfigHandler(this);
482 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700483 mcastHandler = new McastHandler(this);
484 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800485 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700486 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800487 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800488 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100489 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700490
Charles Chan3e783d02016-02-26 22:19:52 -0800491 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700492 cfgService.registerConfigFactory(deviceConfigFactory);
493 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700494 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700495 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800496 log.info("Configuring network before adding listeners");
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200497
Charles Chan132393a2018-01-04 14:26:07 -0800498 cfgListener.configureNetwork();
499
Charles Chan5270ed02016-01-30 23:22:37 -0800500 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700501 packetService.addProcessor(processor, PacketProcessor.director(2));
502 linkService.addListener(linkListener);
503 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700504 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700505 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100506 topologyService.addListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700507 mastershipService.addListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700508 clusterService.addListener(clusterListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700509
Charles Chanb39777c2018-03-09 15:53:44 -0800510 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800511 l2TunnelHandler.init();
512
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200513 networkConfigCompletion.whenComplete((value, ex) -> {
514 //setting to null for easier fall through
515 networkConfigCompletion = null;
516 //process all queued events
Charles Chan10b2fee2018-04-21 00:44:29 -0700517 queuedEvents.forEach(event -> {
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200518 mainEventExecutor.execute(new InternalEventHandler(event));
519 });
520 });
521
sanghob35a6192015-04-01 13:05:26 -0700522 log.info("Started");
523 }
524
Saurav Das45f48152018-01-18 12:07:33 -0800525 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700526 return new KryoNamespace.Builder()
527 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700528 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800529 VlanNextObjectiveStoreKey.class,
530 DestinationSet.class,
Andreas Pantelopoulos67e09ae2018-05-29 13:11:14 -0700531 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800532 NextNeighbors.class,
533 Tunnel.class,
534 DefaultTunnel.class,
535 Policy.class,
536 TunnelPolicy.class,
537 Policy.Type.class,
538 PortNextObjectiveStoreKey.class,
539 XConnectStoreKey.class,
540 L2Tunnel.class,
541 L2TunnelPolicy.class,
542 DefaultL2Tunnel.class,
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700543 DefaultL2TunnelPolicy.class,
544 DummyVlanIdStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700545 );
546 }
547
sanghob35a6192015-04-01 13:05:26 -0700548 @Deactivate
549 protected void deactivate() {
Charles Chan50bb6ef2018-04-18 18:41:05 -0700550 mainEventExecutor.shutdown();
551 hostEventExecutor.shutdown();
552 routeEventExecutor.shutdown();
553 mcastEventExecutor.shutdown();
Charles Chan07f15f22018-05-08 21:35:50 -0700554 packetExecutor.shutdown();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700555
Ray Milkey749996b2018-05-11 09:59:19 -0700556 mainEventExecutor = null;
557 hostEventExecutor = null;
558 routeEventExecutor = null;
559 mcastEventExecutor = null;
560 packetExecutor = null;
561
Charles Chand6832882015-10-05 17:50:33 -0700562 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700563 cfgService.unregisterConfigFactory(deviceConfigFactory);
564 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700565 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700566 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800567 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700568
Charles Chanc7a8a682017-06-19 00:43:31 -0700569 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700570 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700571 linkService.removeListener(linkListener);
572 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700573 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700574 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100575 topologyService.removeListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700576 mastershipService.removeListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700577 clusterService.removeListener(clusterListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700578
Charles Chan0aa674e2017-02-23 15:44:08 -0800579 neighbourResolutionService.unregisterNeighbourHandlers(appId);
580
sanghob35a6192015-04-01 13:05:26 -0700581 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700582 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700583 deviceListener = null;
Charles Chan6577f612018-04-19 13:10:01 -0700584 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chanb8e10c82015-10-14 11:24:40 -0700585 groupHandlerMap.clear();
Saurav Dasc6ff8f02018-04-23 18:42:12 -0700586 defaultRoutingHandler.shutdown();
Charles Chanb8e10c82015-10-14 11:24:40 -0700587
Saurav Das7bcbe702017-06-13 15:35:54 -0700588 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800589 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700590 portNextObjStore.destroy();
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700591 dummyVlanIdStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700592 tunnelStore.destroy();
593 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100594
595 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700596 log.info("Stopped");
597 }
598
Charles Chan47933752017-11-30 15:37:50 -0800599 @Modified
600 private void modified(ComponentContext context) {
601 Dictionary<?, ?> properties = context.getProperties();
602 if (properties == null) {
603 return;
604 }
605
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700606 String strActiveProbing = Tools.get(properties, "activeProbing");
607 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan47933752017-11-30 15:37:50 -0800608 if (expectActiveProbing != activeProbing) {
609 activeProbing = expectActiveProbing;
610 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
611 }
Saurav Das9a554292018-04-27 18:42:30 -0700612
613 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
614 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
615 if (expectSingleHomedDown != singleHomedDown) {
616 singleHomedDown = expectSingleHomedDown;
617 log.info("{} downing of single homed hosts for lost uplinks",
618 singleHomedDown ? "Enabling" : "Disabling");
619 if (singleHomedDown && linkHandler != null) {
620 hostService.getHosts().forEach(host -> host.locations()
621 .forEach(loc -> {
622 if (interfaceService.isConfigured(loc)) {
623 linkHandler.checkUplinksForHost(loc);
624 }
625 }));
626 } else {
627 log.warn("Disabling singleHomedDown does not re-enable already "
628 + "downed ports for single-homed hosts");
629 }
630 }
Andreas Pantelopoulosb2518012018-06-18 12:50:35 -0700631
632 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
633 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
634 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
635 respondToUnknownHosts = expectRespondToUnknownHosts;
636 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
637 }
Charles Chan57465d32018-07-19 14:55:31 -0700638
Charles Chanb67dfdd2018-07-24 16:40:35 -0700639 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
640 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
641 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
642 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
643 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan57465d32018-07-19 14:55:31 -0700644
Charles Chanb67dfdd2018-07-24 16:40:35 -0700645 if (routeDoubleTaggedHosts) {
Charles Chan57465d32018-07-19 14:55:31 -0700646 hostHandler.populateAllDoubleTaggedHost();
647 } else {
648 hostHandler.revokeAllDoubleTaggedHost();
649 }
650 }
Saurav Das09c2c4d2018-08-13 15:34:26 -0700651
652 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
653 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
654 if (defIntVlan != defaultInternalVlan) {
655 if (canUseVlanId(defIntVlan)) {
656 log.warn("Default internal vlan value changed from {} to {}.. "
657 + "re-programming filtering rules, but NOT any groups already "
658 + "created with the former value", defaultInternalVlan, defIntVlan);
659 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
660 defaultInternalVlan = defIntVlan;
661 routingRulePopulator
662 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
663 VlanId.vlanId((short) defIntVlan));
664 } else {
665 log.warn("Cannot change default internal vlan to unusable "
666 + "value {}", defIntVlan);
667 }
668 }
669
670 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
671 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
672 if (pwTxpVlan != pwTransportVlan) {
673 if (canUseVlanId(pwTxpVlan)) {
674 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
675 + "re-programming filtering rules, but NOT any groups already "
676 + "created with the former value", pwTransportVlan,
677 pwTxpVlan);
678 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
679 pwTransportVlan = pwTxpVlan;
680 routingRulePopulator
681 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
682 VlanId.vlanId((short) pwTxpVlan));
683 } else {
684 log.warn("Cannot change pseudowire transport vlan to unusable "
685 + "value {}", pwTxpVlan);
686 }
687 }
688
689 }
690
691 /**
692 * Returns true if given vlan id is not being used in the system currently,
693 * either as one of the default system wide vlans or as one of the
694 * configured interface vlans.
695 *
696 * @param vlanId given vlan id
697 * @return true if vlan is not currently in use
698 */
699 public boolean canUseVlanId(int vlanId) {
700 if (vlanId >= 4095 || vlanId <= 1) {
701 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
702 vlanId);
703 return false;
704 }
705
706 VlanId vid = VlanId.vlanId((short) vlanId);
707 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
708 log.warn("Vlan id {} value is already in use system-wide. "
709 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
710 getDefaultInternalVlan(), getPwTransportVlan());
711 return false;
712 }
713
714 if (interfaceService.inUse(vid)) {
715 log.warn("Vlan id {} value is already in use on a configured "
716 + "interface in the system", vlanId);
717 return false;
718 }
719 return true;
720 }
721
722 /**
723 * Returns the VlanId assigned internally by default to unconfigured ports.
724 *
725 * @return the default internal vlan id
726 */
727 public VlanId getDefaultInternalVlan() {
728 return VlanId.vlanId((short) defaultInternalVlan);
729 }
730
731 /**
732 * Returns the Vlan id used to transport pseudowire traffic across the
733 * network.
734 *
735 * @return the pseudowire transport vlan id
736 */
737 public VlanId getPwTransportVlan() {
738 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan47933752017-11-30 15:37:50 -0800739 }
740
sangho1e575652015-05-14 00:39:53 -0700741 @Override
742 public List<Tunnel> getTunnels() {
743 return tunnelHandler.getTunnels();
744 }
745
746 @Override
sangho71abe1b2015-06-29 14:58:47 -0700747 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
748 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700749 }
750
751 @Override
sangho71abe1b2015-06-29 14:58:47 -0700752 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700753 for (Policy policy: policyHandler.getPolicies()) {
754 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
755 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
756 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
757 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700758 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700759 }
760 }
761 }
sangho71abe1b2015-06-29 14:58:47 -0700762 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700763 }
764
765 @Override
sangho71abe1b2015-06-29 14:58:47 -0700766 public PolicyHandler.Result removePolicy(Policy policy) {
767 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700768 }
769
770 @Override
sangho71abe1b2015-06-29 14:58:47 -0700771 public PolicyHandler.Result createPolicy(Policy policy) {
772 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700773 }
774
775 @Override
776 public List<Policy> getPolicies() {
777 return policyHandler.getPolicies();
778 }
779
Saurav Das59232cf2016-04-27 18:35:50 -0700780 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700781 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
782 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700783 }
784
785 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800786 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700787 return l2TunnelHandler.getL2Tunnels();
788 }
789
790 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800791 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700792 return l2TunnelHandler.getL2Policies();
793 }
794
Saurav Das5a356042018-04-06 20:16:01 -0700795 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700796 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700797 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
798
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700799 // get both added and pending pseudowires
800 List<L2TunnelDescription> pseudowires = new ArrayList<>();
801 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
802 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700803 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700804
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700805 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
806
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700807 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
808 L2TunnelHandler.Result res;
809 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
810 res = addPseudowire(pw);
811 if (res != L2TunnelHandler.Result.SUCCESS) {
812 log.error("Pseudowire with id {} can not be instantiated !", res);
813 retRes = res;
814 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700815 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700816
817 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700818 }
819
820 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800821 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700822 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700823 }
824
825 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800826 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700827 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700828 }
829
830 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700831 public void rerouteNetwork() {
832 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700833 }
834
Charles Chanc81c45b2016-10-20 17:02:44 -0700835 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800836 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
837 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800838 deviceConfiguration.getRouters().forEach(device ->
839 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700840 return deviceSubnetMap;
841 }
842
Saurav Dasc88d4662017-05-15 15:34:25 -0700843
844 @Override
845 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
846 if (defaultRoutingHandler != null) {
847 return defaultRoutingHandler.getCurrentEmcpSpgMap();
848 } else {
849 return null;
850 }
851 }
852
853 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700854 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
855 if (dsNextObjStore != null) {
856 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700857 } else {
858 return ImmutableMap.of();
859 }
860 }
861
Saurav Dasceccf242017-08-03 18:30:35 -0700862 @Override
863 public void verifyGroups(DeviceId id) {
864 DefaultGroupHandler gh = groupHandlerMap.get(id);
865 if (gh != null) {
866 gh.triggerBucketCorrector();
867 }
868 }
869
Saurav Dasc568c342018-01-25 09:49:01 -0800870 @Override
871 public ImmutableMap<Link, Boolean> getSeenLinks() {
872 return linkHandler.getSeenLinks();
873 }
874
875 @Override
876 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
877 return linkHandler.getDownedPorts();
878 }
879
Pier Luigib29144d2018-01-15 18:06:43 +0100880 @Override
881 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
882 return mcastHandler.getMcastNextIds(mcastIp);
883 }
884
885 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100886 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100887 return mcastHandler.getMcastRoles(mcastIp);
888 }
889
890 @Override
Pier3e793752018-04-19 16:47:06 +0200891 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
892 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
893 }
894
895 @Override
Pier Luigib29144d2018-01-15 18:06:43 +0100896 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
897 return mcastHandler.getMcastPaths(mcastIp);
898 }
899
Pier96f63cb2018-04-17 16:29:56 +0200900 @Override
Pierb1fe7382018-04-17 17:25:22 +0200901 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
902 ConnectPoint sourcecp) {
903 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
904 }
905
906 @Override
Pier96f63cb2018-04-17 16:29:56 +0200907 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
908 return mcastHandler.getMcastLeaders(mcastIp);
909 }
910
Charles Chan8bc75ee2018-04-17 18:56:53 -0700911 @Override
912 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
913 return defaultRoutingHandler == null ? ImmutableMap.of() :
914 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
915 }
916
917 @Override
918 public Map<DeviceId, Boolean> getShouldProgramCache() {
919 return defaultRoutingHandler == null ? ImmutableMap.of() :
920 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
921 }
922
Charles Chanc7b3c452018-06-19 20:31:57 -0700923 @Override
Ray Milkeye4afdb52017-04-05 09:42:04 -0700924 public ApplicationId appId() {
925 return appId;
926 }
927
928 /**
929 * Returns the device configuration.
930 *
931 * @return device configuration
932 */
933 public DeviceConfiguration deviceConfiguration() {
934 return deviceConfiguration;
935 }
936
937 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700938 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700939 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700940 *
941 * @return next objective ID store
942 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700943 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
944 dsNextObjStore() {
945 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700946 }
947
948 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700949 * Per device next objective ID store with (device id + vlanid) as key.
950 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700951 *
952 * @return vlan next object store
953 */
954 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
955 return vlanNextObjStore;
956 }
957
958 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700959 * Per device next objective ID store with (device id + port + treatment + meta) as key.
960 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700961 *
962 * @return port next object store.
963 */
964 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
965 return portNextObjStore;
966 }
967
968 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700969 * Per port dummy VLAN ID store with (connect point + ip address) as key.
970 * Used to keep track on dummy VLAN ID allocation.
971 *
972 * @return dummy vlan id store.
973 */
974 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
975 return dummyVlanIdStore;
976 }
977
978 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700979 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
980 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700981 *
982 * @return MPLS-ECMP value
983 */
984 public boolean getMplsEcmp() {
985 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
986 .getConfig(this.appId, SegmentRoutingAppConfig.class);
987 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
988 }
989
990 /**
sanghof9d0bf12015-05-19 11:57:42 -0700991 * Returns the tunnel object with the tunnel ID.
992 *
993 * @param tunnelId Tunnel ID
994 * @return Tunnel reference
995 */
sangho1e575652015-05-14 00:39:53 -0700996 public Tunnel getTunnel(String tunnelId) {
997 return tunnelHandler.getTunnel(tunnelId);
998 }
999
Charles Chanc7b3c452018-06-19 20:31:57 -07001000 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +01001001 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan971d7ba2018-05-01 11:50:20 -07001002 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1003 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -07001004 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1005 }
1006
Charles Chanc7b3c452018-06-19 20:31:57 -07001007 @Override
1008 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001009 SegmentRoutingDeviceConfig deviceConfig =
1010 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1011 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1012 }
Charles Chanc7b3c452018-06-19 20:31:57 -07001013
1014 @Override
Saurav Das9a554292018-04-27 18:42:30 -07001015 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001016 SegmentRoutingDeviceConfig deviceConfig =
1017 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1018 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1019 }
1020
1021 /**
Charles Chan9640c812017-08-23 13:55:39 -07001022 * Returns locations of given resolved route.
1023 *
1024 * @param resolvedRoute resolved route
1025 * @return locations of nexthop. Might be empty if next hop is not found
1026 */
1027 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1028 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1029 return Optional.ofNullable(hostService.getHost(hostId))
1030 .map(Host::locations).orElse(Sets.newHashSet())
1031 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1032 }
1033
1034 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -08001035 * Returns vlan port map of given device.
1036 *
1037 * @param deviceId device id
1038 * @return vlan-port multimap
1039 */
1040 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1041 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1042
1043 interfaceService.getInterfaces().stream()
1044 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1045 .forEach(intf -> {
1046 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -07001047 intf.vlanTagged().forEach(vlanTagged ->
1048 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1049 );
Charles Chan7ffd81f2017-02-08 15:52:08 -08001050 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1051 });
1052 vlanPortMap.removeAll(VlanId.NONE);
1053
1054 return vlanPortMap;
1055 }
1056
1057 /**
Charles Chan59cc16d2017-02-02 16:20:42 -08001058 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -08001059 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -07001060 *
1061 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -08001062 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -08001063 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -07001064 */
Charles Chan65238242017-06-22 18:03:14 -07001065 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -07001066 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -08001067 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1068 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001069 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -08001070 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -08001071 + "device {} not found", deviceId);
1072 return -1;
1073 }
1074 }
1075
1076 /**
1077 * Returns the next objective ID for the given portNumber, given the treatment.
1078 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -07001079 * would result in different objectives. If the next object does not exist,
1080 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -08001081 *
1082 * @param deviceId Device ID
1083 * @param portNum port number on device for which NextObjective is queried
1084 * @param treatment the actions to apply on the packets (should include outport)
1085 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -07001086 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -07001087 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -08001088 */
1089 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1090 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -07001091 TrafficSelector meta,
1092 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -08001093 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1094 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -07001095 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -08001096 } else {
Charles Chane849c192016-01-11 18:28:54 -08001097 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1098 + " not found", deviceId);
1099 return -1;
1100 }
1101 }
1102
Saurav Dasc88d4662017-05-15 15:34:25 -07001103 /**
1104 * Returns the group handler object for the specified device id.
1105 *
1106 * @param devId the device identifier
1107 * @return the groupHandler object for the device id, or null if not found
1108 */
Charles Chan65238242017-06-22 18:03:14 -07001109 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001110 return groupHandlerMap.get(devId);
1111 }
1112
1113 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001114 * Returns the default routing handler object.
1115 *
1116 * @return the default routing handler object
1117 */
1118 public DefaultRoutingHandler getRoutingHandler() {
1119 return defaultRoutingHandler;
1120 }
1121
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001122 /**
1123 * Returns new dummy VLAN ID.
1124 * Dummy VLAN ID should be unique in each connect point.
1125 *
1126 * @param cp connect point
1127 * @param ipAddress IP address
1128 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1129 */
1130 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1131 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1132 dummyVlanIdStore.entrySet().stream().filter(entry ->
1133 (entry.getKey()).connectPoint().equals(cp))
1134 .map(Map.Entry::getValue)
1135 .collect(Collectors.toSet()));
1136
1137 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1138 i -> VlanId.vlanId((short) (i & 0xFFFF))
1139 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1140
1141 if (!dummyVlanId.equals(VlanId.NONE)) {
1142 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1143 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1144 } else {
1145 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1146 }
1147 return dummyVlanId;
1148 }
1149
1150
sanghob35a6192015-04-01 13:05:26 -07001151 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001152 @Override
1153 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -07001154 packetExecutor.execute(() -> processPacketInternal(context));
1155 }
sanghob35a6192015-04-01 13:05:26 -07001156
Charles Chan07f15f22018-05-08 21:35:50 -07001157 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001158 if (context.isHandled()) {
1159 return;
1160 }
1161
1162 InboundPacket pkt = context.inPacket();
1163 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001164
1165 if (ethernet == null) {
1166 return;
1167 }
1168
Saurav Das7bcbe702017-06-13 15:35:54 -07001169 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1170 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001171 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001172 log.warn("Received unexpected ARP packet on {}",
1173 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001174 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001175 return;
sanghob35a6192015-04-01 13:05:26 -07001176 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001177 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1178 //ipHandler.addToPacketBuffer(ipv4Packet);
1179 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1180 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001181 } else {
Charles Chan50035632017-01-13 17:20:44 -08001182 // NOTE: We don't support IP learning at this moment so this
1183 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001184 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001185 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001186 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1187 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001188 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001189 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001190 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1191 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1192 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1193 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1194 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1195 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001196 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001197 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001198 }
1199 } else {
1200 // NOTE: We don't support IP learning at this moment so this
1201 // is not necessary. Also it causes duplication of DHCPv6 packets.
1202 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1203 }
sanghob35a6192015-04-01 13:05:26 -07001204 }
1205 }
1206 }
1207
sanghob35a6192015-04-01 13:05:26 -07001208 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001209 private Event event;
1210
1211 InternalEventHandler(Event event) {
1212 this.event = event;
1213 }
1214
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001215 @Override
sanghob35a6192015-04-01 13:05:26 -07001216 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001217 try {
1218 // TODO We should also change SR routing and PW to listen to TopologyEvents
1219 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1220 event.type() == LinkEvent.Type.LINK_UPDATED) {
1221 linkHandler.processLinkAdded((Link) event.subject());
1222 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1223 linkHandler.processLinkRemoved((Link) event.subject());
1224 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1225 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1226 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1227 DeviceId deviceId = ((Device) event.subject()).id();
1228 if (deviceService.isAvailable(deviceId)) {
1229 log.info("** DEVICE UP Processing device event {} "
1230 + "for available device {}",
1231 event.type(), ((Device) event.subject()).id());
1232 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001233 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001234 log.info(" ** DEVICE DOWN Processing device event {}"
1235 + " for unavailable device {}",
1236 event.type(), ((Device) event.subject()).id());
1237 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001238 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001239 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1240 // typically these calls come when device is added first time
1241 // so port filtering rules are handled at the device_added event.
1242 // port added calls represent all ports on the device,
1243 // enabled or not.
1244 log.trace("** PORT ADDED {}/{} -> {}",
1245 ((DeviceEvent) event).subject().id(),
1246 ((DeviceEvent) event).port().number(),
1247 event.type());
1248 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1249 // these calls happen for every subsequent event
1250 // ports enabled, disabled, switch goes away, comes back
1251 log.info("** PORT UPDATED {}/{} -> {}",
1252 event.subject(),
1253 ((DeviceEvent) event).port(),
1254 event.type());
Saurav Das9a554292018-04-27 18:42:30 -07001255 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001256 ((DeviceEvent) event).port());
1257 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1258 // Process topology event, needed for all modules relying on
1259 // topology service for path computation
1260 TopologyEvent topologyEvent = (TopologyEvent) event;
1261 log.info("Processing topology event {}, topology age {}, reasons {}",
1262 event.type(), topologyEvent.subject().time(),
1263 topologyEvent.reasons().size());
1264 topologyHandler.processTopologyChange(topologyEvent.reasons());
1265 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1266 hostHandler.processHostAddedEvent((HostEvent) event);
1267 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1268 hostHandler.processHostMovedEvent((HostEvent) event);
1269 routeHandler.processHostMovedEvent((HostEvent) event);
1270 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1271 hostHandler.processHostRemovedEvent((HostEvent) event);
1272 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1273 hostHandler.processHostUpdatedEvent((HostEvent) event);
1274 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1275 routeHandler.processRouteAdded((RouteEvent) event);
1276 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1277 routeHandler.processRouteUpdated((RouteEvent) event);
1278 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1279 routeHandler.processRouteRemoved((RouteEvent) event);
1280 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1281 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1282 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1283 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1284 event.type() == McastEvent.Type.SINKS_ADDED ||
1285 event.type() == McastEvent.Type.SINKS_REMOVED ||
1286 event.type() == McastEvent.Type.ROUTE_ADDED ||
1287 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1288 mcastHandler.processMcastEvent((McastEvent) event);
1289 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1290 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1291 Class configClass = netcfgEvent.configClass();
1292 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1293 appCfgHandler.processAppConfigAdded(netcfgEvent);
1294 log.info("App config event .. configuring network");
1295 cfgListener.configureNetwork();
1296 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1297 log.info("Segment Routing Device Config added for {}", event.subject());
1298 cfgListener.configureNetwork();
1299 } else if (configClass.equals(XConnectConfig.class)) {
1300 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1301 } else if (configClass.equals(InterfaceConfig.class)) {
1302 log.info("Interface Config added for {}", event.subject());
1303 cfgListener.configureNetwork();
1304 } else {
1305 log.error("Unhandled config class: {}", configClass);
1306 }
1307 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1308 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1309 Class configClass = netcfgEvent.configClass();
1310 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1311 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1312 log.info("App config event .. configuring network");
1313 cfgListener.configureNetwork();
1314 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1315 log.info("Segment Routing Device Config updated for {}", event.subject());
1316 createOrUpdateDeviceConfiguration();
1317 } else if (configClass.equals(XConnectConfig.class)) {
1318 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1319 } else if (configClass.equals(InterfaceConfig.class)) {
1320 log.info("Interface Config updated for {}", event.subject());
1321 createOrUpdateDeviceConfiguration();
1322 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1323 (InterfaceConfig) netcfgEvent.prevConfig().get());
1324 } else {
1325 log.error("Unhandled config class: {}", configClass);
1326 }
1327 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1328 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1329 Class configClass = netcfgEvent.configClass();
1330 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1331 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1332 log.info("App config event .. configuring network");
1333 cfgListener.configureNetwork();
1334 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1335 // TODO Handle sr device config removal
1336 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1337 } else if (configClass.equals(XConnectConfig.class)) {
1338 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1339 } else if (configClass.equals(InterfaceConfig.class)) {
1340 // TODO Handle interface removal
1341 log.info("InterfaceConfig removal is not handled in current implementation");
1342 } else {
1343 log.error("Unhandled config class: {}", configClass);
1344 }
Saurav Das201762d2018-04-21 17:19:48 -07001345 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1346 MastershipEvent me = (MastershipEvent) event;
1347 DeviceId deviceId = me.subject();
1348 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1349 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1350 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1351 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1352 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1353 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001354 } else {
1355 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001356 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001357 } catch (Exception e) {
1358 log.error("SegmentRouting event handler thread thrown an exception: {}",
1359 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001360 }
sanghob35a6192015-04-01 13:05:26 -07001361 }
1362 }
1363
Saurav Das45f48152018-01-18 12:07:33 -08001364 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001365 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001366
1367 // NOTE: Punt ARP/NDP even when the device is not configured.
1368 // Host learning without network config is required for CORD config generator.
1369 routingRulePopulator.populateIpPunts(device.id());
1370 routingRulePopulator.populateArpNdpPunts(device.id());
1371
Charles Chan0b4e6182015-11-03 10:42:14 -08001372 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001373 log.warn("Device configuration unavailable. Device {} will be "
1374 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001375 return;
1376 }
Charles Chan2199c302016-04-23 17:36:10 -07001377 processDeviceAddedInternal(device.id());
1378 }
1379
1380 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001381 // Irrespective of whether the local is a MASTER or not for this device,
1382 // we need to create a SR-group-handler instance. This is because in a
1383 // multi-instance setup, any instance can initiate forwarding/next-objectives
1384 // for any switch (even if this instance is a SLAVE or not even connected
1385 // to the switch). To handle this, a default-group-handler instance is necessary
1386 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001387 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1388 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001389 DefaultGroupHandler groupHandler;
1390 try {
1391 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001392 createGroupHandler(deviceId,
1393 appId,
1394 deviceConfiguration,
1395 linkService,
1396 flowObjectiveService,
1397 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001398 } catch (DeviceConfigNotFoundException e) {
1399 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1400 return;
1401 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001402 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001403 deviceId);
1404 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001405 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001406
Charles Chan2199c302016-04-23 17:36:10 -07001407 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001408 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001409 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001410 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001411 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001412 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001413 }
Charles Chan5270ed02016-01-30 23:22:37 -08001414
Charles Chan03a73e02016-10-24 14:52:01 -07001415 appCfgHandler.init(deviceId);
Charles Chan94549652018-04-29 18:11:37 -07001416 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1417 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001418 }
1419
Saurav Das80980c72016-03-23 11:22:49 -07001420 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001421 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001422 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001423 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001424 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001425 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001426 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001427 portNextObjStore.entrySet().stream()
1428 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001429 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001430 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001431
Saurav Dasceccf242017-08-03 18:30:35 -07001432 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1433 if (gh != null) {
1434 gh.shutdown();
1435 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001436 // Note that a switch going down is associated with all of its links
1437 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001438 // while the link-downs are ignored. We cannot rely on the ordering of
1439 // events - i.e we cannot expect all link-downs to come before the
1440 // switch down - so we purge all seen-links for the switch before
1441 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001442 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001443 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001444 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001445 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001446
1447 // Cleanup all internal groupHandler stores for this device. Should be
1448 // done after all rerouting or rehashing has been completed
1449 groupHandlerMap.entrySet()
1450 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001451 }
1452
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001453 /**
1454 * Purge the destinationSet nextObjective store of entries with this device
1455 * as key. Erases app-level knowledge of hashed groups in this device.
1456 *
1457 * @param devId the device identifier
1458 */
Saurav Das201762d2018-04-21 17:19:48 -07001459 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001460 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das201762d2018-04-21 17:19:48 -07001461 dsNextObjStore.entrySet().stream()
1462 .filter(entry -> entry.getKey().deviceId().equals(devId))
1463 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1464 }
1465
Saurav Das9a554292018-04-27 18:42:30 -07001466 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001467 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1468 log.warn("Device configuration uploading. Not handling port event for"
1469 + "dev: {} port: {}", device.id(), port.number());
1470 return;
1471 }
Saurav Das018605f2017-02-18 14:05:44 -08001472
Saurav Das9a554292018-04-27 18:42:30 -07001473 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1474 lastEdgePortEvent = Instant.now();
1475 }
1476
Saurav Das018605f2017-02-18 14:05:44 -08001477 if (!mastershipService.isLocalMaster(device.id())) {
1478 log.debug("Not master for dev:{} .. not handling port updated event"
1479 + "for port {}", device.id(), port.number());
1480 return;
1481 }
Saurav Das9a554292018-04-27 18:42:30 -07001482 processPortUpdated(device.id(), port);
1483 }
Saurav Das018605f2017-02-18 14:05:44 -08001484
Saurav Das9a554292018-04-27 18:42:30 -07001485 /**
1486 * Adds or remove filtering rules for the given switchport. If switchport is
1487 * an edge facing port, additionally handles host probing and broadcast
1488 * rules. Must be called by local master of device.
1489 *
1490 * @param deviceId the device identifier
1491 * @param port the port to update
1492 */
1493 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001494 // first we handle filtering rules associated with the port
1495 if (port.isEnabled()) {
1496 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das9a554292018-04-27 18:42:30 -07001497 deviceId, port.number());
1498 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001499 } else {
1500 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das9a554292018-04-27 18:42:30 -07001501 deviceId, port.number());
1502 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001503 }
Saurav Das1a129a02016-11-18 15:21:57 -08001504
1505 // portUpdated calls are for ports that have gone down or up. For switch
1506 // to switch ports, link-events should take care of any re-routing or
1507 // group editing necessary for port up/down. Here we only process edge ports
1508 // that are already configured.
Saurav Das9a554292018-04-27 18:42:30 -07001509 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan971d7ba2018-05-01 11:50:20 -07001510 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1511 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1512 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001513
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001514 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001515 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das9a554292018-04-27 18:42:30 -07001516 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001517 return;
1518 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001519 if (untaggedVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001520 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001521 }
1522 if (nativeVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001523 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001524 }
1525 if (!taggedVlans.isEmpty()) {
Saurav Das9a554292018-04-27 18:42:30 -07001526 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001527 }
Saurav Das1a129a02016-11-18 15:21:57 -08001528 }
1529
Saurav Das9a554292018-04-27 18:42:30 -07001530 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001531 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001532 boolean portUp = port.isEnabled();
1533 if (portUp) {
Saurav Das9a554292018-04-27 18:42:30 -07001534 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001535 port.number(), vlanId);
Charles Chan94549652018-04-29 18:11:37 -07001536 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001537 } else {
Saurav Das9a554292018-04-27 18:42:30 -07001538 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001539 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001540 }
1541
Saurav Das9a554292018-04-27 18:42:30 -07001542 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001543 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001544 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001545 } else {
1546 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das9a554292018-04-27 18:42:30 -07001547 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001548 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001549 }
1550 }
sangho1e575652015-05-14 00:39:53 -07001551
Charles Chan27fe1a52017-10-20 16:06:55 -07001552 private void createOrUpdateDeviceConfiguration() {
1553 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001554 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001555 deviceConfiguration = new DeviceConfiguration(this);
1556 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001557 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001558 deviceConfiguration.updateConfig();
1559 }
1560 }
1561
Charles Chan50bb6ef2018-04-18 18:41:05 -07001562 private void createOrUpdateDefaultRoutingHandler() {
1563 if (defaultRoutingHandler == null) {
1564 log.info("Creating new DefaultRoutingHandler");
1565 defaultRoutingHandler = new DefaultRoutingHandler(this);
1566 } else {
1567 log.info("Updating DefaultRoutingHandler");
1568 defaultRoutingHandler.update(this);
1569 }
1570 }
1571
Pier Ventre10bd8d12016-11-26 21:05:22 -08001572 /**
1573 * Registers the given connect point with the NRS, this is necessary
1574 * to receive the NDP and ARP packets from the NRS.
1575 *
1576 * @param portToRegister connect point to register
1577 */
1578 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001579 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001580 portToRegister,
1581 neighbourHandler,
1582 appId
1583 );
1584 }
1585
Charles Chand6832882015-10-05 17:50:33 -07001586 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001587 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001588 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001589
Charles Chane849c192016-01-11 18:28:54 -08001590 /**
1591 * Constructs the internal network config listener.
1592 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001593 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001594 */
Charles Chan65238242017-06-22 18:03:14 -07001595 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001596 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001597 }
1598
Charles Chane849c192016-01-11 18:28:54 -08001599 /**
1600 * Reads network config and initializes related data structure accordingly.
1601 */
Charles Chan47933752017-11-30 15:37:50 -08001602 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001603 log.info("Configuring network ...");
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001604
1605 // Setting handling of network configuration events completable future
1606 // The completable future is needed because of the async behaviour of the configureNetwork,
1607 // listener registration and event arrival
1608 // Enables us to buffer the events and execute them when the configure network is done.
1609 networkConfigCompletion = new CompletableFuture<>();
1610
1611 // add a small delay to absorb multiple network config added notifications
1612 if (!programmingScheduled.get()) {
1613 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1614 programmingScheduled.set(true);
1615 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1616 }
1617
Charles Chan27fe1a52017-10-20 16:06:55 -07001618 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001619
Charles Chan2c15aca2016-11-09 20:51:44 -08001620 arpHandler = new ArpHandler(srManager);
1621 icmpHandler = new IcmpHandler(srManager);
1622 ipHandler = new IpHandler(srManager);
1623 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chan50bb6ef2018-04-18 18:41:05 -07001624 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001625
1626 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1627 groupHandlerMap, tunnelStore);
1628 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1629 flowObjectiveService,
1630 tunnelHandler, policyStore);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001631 networkConfigCompletion.complete(true);
1632
Charles Chan2199c302016-04-23 17:36:10 -07001633 mcastHandler.init();
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001634
Charles Chan4636be02015-10-07 14:21:45 -07001635 }
1636
Charles Chand6832882015-10-05 17:50:33 -07001637 @Override
1638 public void event(NetworkConfigEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001639 if (mainEventExecutor == null) {
1640 return;
1641 }
Charles Chan7a888e82018-03-21 16:57:47 -07001642 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1643 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1644 switch (event.type()) {
1645 case CONFIG_ADDED:
1646 case CONFIG_UPDATED:
1647 case CONFIG_REMOVED:
1648 log.trace("Schedule Network Config event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001649 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1650 mainEventExecutor.execute(new InternalEventHandler(event));
1651 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001652 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001653 }
Charles Chan7a888e82018-03-21 16:57:47 -07001654 break;
1655 default:
1656 break;
Charles Chand6832882015-10-05 17:50:33 -07001657 }
1658 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001659
Charles Chan50443e82018-01-03 16:26:32 -08001660 @Override
1661 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001662 if (event.type() == CONFIG_REGISTERED ||
1663 event.type() == CONFIG_UNREGISTERED) {
1664 log.debug("Ignore event {} due to type mismatch", event);
1665 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001666 }
Saurav Dase7f51012018-02-09 17:26:45 -08001667
1668 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1669 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1670 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001671 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001672 log.debug("Ignore event {} due to class mismatch", event);
1673 return false;
1674 }
1675
1676 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001677 }
1678
Saurav Das7bcbe702017-06-13 15:35:54 -07001679 private final class ConfigChange implements Runnable {
1680 @Override
1681 public void run() {
1682 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001683 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001684 for (Device device : deviceService.getDevices()) {
1685 processDeviceAdded(device);
1686 }
1687 defaultRoutingHandler.startPopulationProcess();
1688 }
1689 }
Charles Chand6832882015-10-05 17:50:33 -07001690 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001691
Charles Chan7a888e82018-03-21 16:57:47 -07001692 private class InternalLinkListener implements LinkListener {
1693 @Override
1694 public void event(LinkEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001695 if (mainEventExecutor == null) {
1696 return;
1697 }
Charles Chan7a888e82018-03-21 16:57:47 -07001698 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1699 event.type() == LinkEvent.Type.LINK_UPDATED ||
1700 event.type() == LinkEvent.Type.LINK_REMOVED) {
1701 log.trace("Schedule Link event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001702 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1703 mainEventExecutor.execute(new InternalEventHandler(event));
1704 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001705 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001706 }
Charles Chan7a888e82018-03-21 16:57:47 -07001707 }
1708 }
1709 }
1710
1711 private class InternalDeviceListener implements DeviceListener {
1712 @Override
1713 public void event(DeviceEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001714 if (mainEventExecutor == null) {
1715 return;
1716 }
Charles Chan7a888e82018-03-21 16:57:47 -07001717 switch (event.type()) {
1718 case DEVICE_ADDED:
1719 case PORT_UPDATED:
1720 case PORT_ADDED:
1721 case DEVICE_UPDATED:
1722 case DEVICE_AVAILABILITY_CHANGED:
1723 log.trace("Schedule Device event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001724 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1725 mainEventExecutor.execute(new InternalEventHandler(event));
1726 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001727 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001728 }
Charles Chan7a888e82018-03-21 16:57:47 -07001729 break;
1730 default:
1731 }
1732 }
1733 }
1734
1735 private class InternalTopologyListener implements TopologyListener {
1736 @Override
1737 public void event(TopologyEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001738 if (mainEventExecutor == null) {
1739 return;
1740 }
Charles Chan7a888e82018-03-21 16:57:47 -07001741 switch (event.type()) {
1742 case TOPOLOGY_CHANGED:
1743 log.trace("Schedule Topology event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001744 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1745 mainEventExecutor.execute(new InternalEventHandler(event));
1746 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001747 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001748 }
Charles Chan7a888e82018-03-21 16:57:47 -07001749 break;
1750 default:
1751 }
1752 }
1753 }
1754
Charles Chan68aa62d2015-11-09 16:37:23 -08001755 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001756 @Override
1757 public void event(HostEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001758 if (hostEventExecutor == null) {
1759 return;
1760 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001761 switch (event.type()) {
1762 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001763 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001764 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001765 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001766 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001767 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001768 break;
1769 default:
1770 log.warn("Unsupported host event type: {}", event.type());
1771 break;
1772 }
1773 }
1774 }
1775
Charles Chand55e84d2016-03-30 17:54:24 -07001776 private class InternalMcastListener implements McastListener {
1777 @Override
1778 public void event(McastEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001779 if (mcastEventExecutor == null) {
1780 return;
1781 }
Charles Chand55e84d2016-03-30 17:54:24 -07001782 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001783 case SOURCES_ADDED:
1784 case SOURCES_REMOVED:
1785 case SINKS_ADDED:
1786 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001787 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001788 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001789 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001790 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001791 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001792 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001793 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001794 break;
1795 }
1796 }
1797 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001798
Charles Chan03a73e02016-10-24 14:52:01 -07001799 private class InternalRouteEventListener implements RouteListener {
1800 @Override
1801 public void event(RouteEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001802 if (routeEventExecutor == null) {
1803 return;
1804 }
Charles Chan03a73e02016-10-24 14:52:01 -07001805 switch (event.type()) {
1806 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001807 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001808 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001809 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001810 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001811 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001812 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001813 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001814 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001815 break;
1816 }
1817 }
1818 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001819
Charles Chan50bb6ef2018-04-18 18:41:05 -07001820 private class InternalMastershipListener implements MastershipListener {
1821 @Override
1822 public void event(MastershipEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001823 if (mainEventExecutor == null) {
1824 return;
1825 }
Charles Chan50bb6ef2018-04-18 18:41:05 -07001826 switch (event.type()) {
Saurav Das201762d2018-04-21 17:19:48 -07001827 case MASTER_CHANGED:
1828 log.debug("Mastership event: {}/{}", event.subject(),
1829 event.roleInfo());
1830 mainEventExecutor.execute(new InternalEventHandler(event));
1831 break;
1832 case BACKUPS_CHANGED:
1833 case SUSPENDED:
1834 default:
1835 log.debug("Mastership event type {} not handled", event.type());
1836 break;
Charles Chan50bb6ef2018-04-18 18:41:05 -07001837 }
1838 }
1839 }
1840
Saurav Das201762d2018-04-21 17:19:48 -07001841 class InternalClusterListener implements ClusterEventListener {
1842 private Instant lastClusterEvent = Instant.EPOCH;
1843
1844 long timeSinceLastClusterEvent() {
1845 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1846 }
1847
1848 @Override
1849 public void event(ClusterEvent event) {
1850 switch (event.type()) {
1851 case INSTANCE_ACTIVATED:
1852 case INSTANCE_ADDED:
1853 case INSTANCE_READY:
1854 log.debug("Cluster event {} ignored", event.type());
1855 break;
1856 case INSTANCE_DEACTIVATED:
1857 case INSTANCE_REMOVED:
1858 log.info("** Cluster event {}", event.type());
1859 lastClusterEvent = Instant.now();
1860 break;
1861 default:
1862 break;
1863 }
1864
1865 }
1866
1867 }
1868
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001869 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1870 try {
1871 Set<Interface> intfs = conf.getInterfaces();
1872 Set<Interface> prevIntfs = prevConf.getInterfaces();
1873
1874 // Now we only handle one interface config at each port.
1875 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1876 log.warn("Interface update aborted - one at a time is allowed, " +
1877 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1878 return;
1879 }
1880
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001881 //The system is in an incoherent state, abort
1882 if (defaultRoutingHandler == null) {
1883 log.warn("Interface update aborted, defaultRoutingHandler is null");
1884 return;
1885 }
1886
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001887 Interface intf = intfs.stream().findFirst().get();
1888 Interface prevIntf = prevIntfs.stream().findFirst().get();
1889
1890 DeviceId deviceId = intf.connectPoint().deviceId();
1891 PortNumber portNum = intf.connectPoint().port();
1892
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001893 removeSubnetConfig(prevIntf.connectPoint(),
1894 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1895 new HashSet<>(intf.ipAddressesList())));
1896
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001897 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1898 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1899 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1900 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1901 // Update filtering objective and L2IG group bucket
1902 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1903 } else {
1904 // RemoveVlanNative
1905 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1906 }
1907 }
1908
1909 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1910 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1911 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1912 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1913 // Update filtering objective and L2IG group bucket
1914 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1915 } else {
1916 // RemoveVlanUntagged
1917 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1918 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001919 }
1920
1921 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1922 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001923 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1924 .filter(i -> !intf.vlanUntagged().equals(i))
1925 .filter(i -> !intf.vlanNative().equals(i))
1926 .forEach(vlanId -> updateVlanConfigInternal(
1927 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001928 }
1929
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001930 if (!intf.vlanNative().equals(VlanId.NONE)
1931 && !prevIntf.vlanNative().equals(intf.vlanNative())
1932 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1933 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1934 // Update filtering objective and L2IG group bucket
1935 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1936 } else {
1937 // AddVlanNative
1938 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1939 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001940 }
1941
1942 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1943 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001944 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1945 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1946 .filter(i -> !prevIntf.vlanNative().equals(i))
1947 .forEach(vlanId -> updateVlanConfigInternal(
1948 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001949 );
1950 }
1951
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001952 if (!intf.vlanUntagged().equals(VlanId.NONE)
1953 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1954 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1955 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1956 // Update filtering objective and L2IG group bucket
1957 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1958 } else {
1959 // AddVlanUntagged
1960 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1961 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001962 }
1963 addSubnetConfig(prevIntf.connectPoint(),
1964 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1965 new HashSet<>(prevIntf.ipAddressesList())));
1966 } catch (ConfigException e) {
1967 log.error("Error in configuration");
1968 }
1969 }
1970
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001971 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1972 VlanId vlanId, boolean pushVlan) {
1973 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1974 if (grpHandler == null) {
1975 log.warn("Failed to retrieve group handler for device {}", deviceId);
1976 return;
1977 }
1978
1979 // Update filtering objective for a single port
1980 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1981 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1982
1983 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1984 // Update L2IG bucket of the port
1985 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1986 } else {
1987 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1988 }
1989 }
1990
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001991 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1992 VlanId vlanId, boolean pushVlan, boolean install) {
1993 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1994 if (grpHandler == null) {
1995 log.warn("Failed to retrieve group handler for device {}", deviceId);
1996 return;
1997 }
1998
1999 // Update filtering objective for a single port
2000 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2001
2002 // Update filtering objective for multicast ingress port
2003 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2004
2005 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2006
2007 if (nextId != -1 && !install) {
2008 // Update next objective for a single port as an output port
2009 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002010 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002011 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan94549652018-04-29 18:11:37 -07002012 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2013 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002014 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2015 // only if there is no port configured on that VLAN ID
2016 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2017 // Remove broadcast forwarding rule for the VLAN
2018 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2019 // Remove L2FG for VLAN
2020 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2021 } else {
2022 // Remove L2IG of the port
2023 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2024 }
2025 } else if (install) {
2026 if (nextId != -1) {
2027 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002028 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002029 } else {
2030 // Create L2FG for VLAN
2031 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2032 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2033 }
Charles Chan94549652018-04-29 18:11:37 -07002034 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2035 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002036 } else {
2037 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2038 }
2039 }
2040
2041 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2042 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2043 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2044
2045 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2046 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2047 .filter(intf -> !intf.connectPoint().equals(cp))
2048 .flatMap(intf -> intf.ipAddressesList().stream())
2049 .collect(Collectors.toSet());
2050 // 1. Partial subnet population
2051 // Remove routing rules for removed subnet from previous configuration,
2052 // which does not also exist in other interfaces in the same device
2053 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2054 .map(InterfaceIpAddress::subnetAddress)
2055 .collect(Collectors.toSet());
2056
2057 defaultRoutingHandler.revokeSubnet(
2058 ipPrefixSet.stream()
2059 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2060 .collect(Collectors.toSet()));
2061
2062 // 2. Interface IP punts
2063 // Remove IP punts for old Intf address
2064 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2065 .map(InterfaceIpAddress::ipAddress)
2066 .collect(Collectors.toSet());
2067 ipAddressSet.stream()
2068 .map(InterfaceIpAddress::ipAddress)
2069 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2070 .forEach(interfaceIpAddress ->
2071 routingRulePopulator.revokeSingleIpPunts(
2072 cp.deviceId(), interfaceIpAddress));
2073
2074 // 3. Host unicast routing rule
2075 // Remove unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002076 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002077 }
2078
2079 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2080 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2081 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2082
2083 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2084 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2085 .filter(intf -> !intf.connectPoint().equals(cp))
2086 .flatMap(intf -> intf.ipAddressesList().stream())
2087 .collect(Collectors.toSet());
2088 // 1. Partial subnet population
2089 // Add routing rules for newly added subnet, which does not also exist in
2090 // other interfaces in the same device
2091 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2092 .map(InterfaceIpAddress::subnetAddress)
2093 .collect(Collectors.toSet());
2094
2095 defaultRoutingHandler.populateSubnet(
2096 Collections.singleton(cp),
2097 ipPrefixSet.stream()
2098 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2099 .collect(Collectors.toSet()));
2100
2101 // 2. Interface IP punts
2102 // Add IP punts for new Intf address
2103 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2104 .map(InterfaceIpAddress::ipAddress)
2105 .collect(Collectors.toSet());
2106 ipAddressSet.stream()
2107 .map(InterfaceIpAddress::ipAddress)
2108 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2109 .forEach(interfaceIpAddress ->
2110 routingRulePopulator.populateSingleIpPunts(
2111 cp.deviceId(), interfaceIpAddress));
2112
2113 // 3. Host unicast routing rule
2114 // Add unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002115 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002116 }
sanghob35a6192015-04-01 13:05:26 -07002117}