blob: 748755c2203f121f85cc9083ad3a10dc5c64d337 [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 Dasc6dc1772018-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 Hyuna76bf032018-04-09 09:40:50 -070044import org.onosproject.cluster.LeadershipService;
Pier4694e092018-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 Chana8487b02018-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 Chan1fa010c2018-08-19 19:21:46 -070078import org.onosproject.net.flowobjective.NextObjective;
Charles Chan68aa62d2015-11-09 16:37:23 -080079import org.onosproject.net.host.HostEvent;
80import org.onosproject.net.host.HostListener;
Charles Chand1d321b2018-06-01 16:33:48 -070081import org.onosproject.net.host.HostProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080082import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070083import org.onosproject.net.host.InterfaceIpAddress;
Pier4694e092018-04-17 16:29:56 +020084import org.onosproject.net.intent.WorkPartitionService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070085import org.onosproject.net.intf.Interface;
86import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080087import org.onosproject.net.link.LinkEvent;
88import org.onosproject.net.link.LinkListener;
89import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070090import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080091import org.onosproject.net.packet.InboundPacket;
92import org.onosproject.net.packet.PacketContext;
93import org.onosproject.net.packet.PacketProcessor;
94import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010095import org.onosproject.net.topology.TopologyEvent;
96import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070097import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070098import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070099import org.onosproject.routeservice.RouteEvent;
100import org.onosproject.routeservice.RouteListener;
101import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700102import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
103import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800104import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700105import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700106import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700107import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700108import org.onosproject.segmentrouting.grouphandler.DestinationSet;
109import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100110import org.onosproject.segmentrouting.mcast.McastHandler;
111import org.onosproject.segmentrouting.mcast.McastRole;
Pier7631c492018-04-19 16:47:06 +0200112import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700116import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800117
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800118import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700119import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800121import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
122
Saurav Das7bcbe702017-06-13 15:35:54 -0700123import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700124import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Pier7631c492018-04-19 16:47:06 +0200125import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700126import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800127import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700128import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan4e87b3e2018-06-19 20:31:57 -0700129import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700130import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700131import org.onosproject.store.service.EventuallyConsistentMap;
132import org.onosproject.store.service.EventuallyConsistentMapBuilder;
133import org.onosproject.store.service.StorageService;
134import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800135import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700136import org.slf4j.Logger;
137import org.slf4j.LoggerFactory;
138
Saurav Dasc6dc1772018-04-21 17:19:48 -0700139import java.time.Instant;
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700140import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800141import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800142import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800143import java.util.HashSet;
144import java.util.List;
145import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800146import java.util.Optional;
147import java.util.Set;
Andrea Campanellaab482f92018-04-17 12:09:34 +0200148import java.util.concurrent.CompletableFuture;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800149import java.util.concurrent.ConcurrentHashMap;
Andrea Campanellaab482f92018-04-17 12:09:34 +0200150import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan595fdc52018-05-08 21:35:50 -0700151import java.util.concurrent.ExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800152import java.util.concurrent.Executors;
153import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800154import java.util.concurrent.TimeUnit;
155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.stream.Collectors;
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700157import java.util.stream.IntStream;
sanghob35a6192015-04-01 13:05:26 -0700158
Charles Chan3e783d02016-02-26 22:19:52 -0800159import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800160import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700161import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
163import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800164
Charles Chane849c192016-01-11 18:28:54 -0800165/**
166 * Segment routing manager.
167 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700168@Service
169@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700170public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700171
Charles Chan2c15aca2016-11-09 20:51:44 -0800172 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700173 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700176 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800179 private NeighbourResolutionService neighbourResolutionService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100182 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700185 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700188 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chand1d321b2018-06-01 16:33:48 -0700191 HostProbingService probingService;
Charles Chan47933752017-11-30 15:37:50 -0800192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100194 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800197 DeviceAdminService deviceAdminService;
198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800200 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100203 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700204
Charles Chan5270ed02016-01-30 23:22:37 -0800205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800206 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700207
208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800209 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700210
211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100212 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700213
214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800215 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700216
217 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700218 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800219
220 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800221 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800222
Saurav Das80980c72016-03-23 11:22:49 -0700223 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800224 public InterfaceService interfaceService;
225
Pier Luigieba73a02018-01-16 10:47:50 +0100226 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
227 public ClusterService clusterService;
228
229 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier4694e092018-04-17 16:29:56 +0200230 public WorkPartitionService workPartitionService;
Pier Luigieba73a02018-01-16 10:47:50 +0100231
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700232 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
233 public LeadershipService leadershipService;
234
Charles Chan4e87b3e2018-06-19 20:31:57 -0700235 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
236 public XconnectService xconnectService;
237
Charles Chan47933752017-11-30 15:37:50 -0800238 @Property(name = "activeProbing", boolValue = true,
239 label = "Enable active probing to discover dual-homed hosts.")
240 boolean activeProbing = true;
241
Saurav Das41b49a92018-04-27 18:42:30 -0700242 @Property(name = "singleHomedDown", boolValue = false,
243 label = "Enable administratively taking down single-homed hosts "
244 + "when all uplinks are gone")
245 boolean singleHomedDown = false;
246
Andreas Pantelopoulos7bf9e442018-06-18 12:50:35 -0700247 @Property(name = "respondToUnknownHosts", boolValue = true,
248 label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
249 boolean respondToUnknownHosts = true;
250
Charles Chan5b9a11a2018-07-24 16:40:35 -0700251 @Property(name = "routeDoubleTaggedHosts", boolValue = false,
252 label = "Program flows and groups to pop and route double tagged hosts")
253 boolean routeDoubleTaggedHosts = false;
Charles Chan3d44eb92018-07-19 14:55:31 -0700254
Saurav Das3c82f192018-08-13 15:34:26 -0700255 private static final int DEFAULT_INTERNAL_VLAN = 4094;
256 @Property(name = "defaultInternalVlan", intValue = DEFAULT_INTERNAL_VLAN,
257 label = "internal vlan assigned by default to unconfigured ports")
258 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN;
259
260 private static final int PW_TRANSPORT_VLAN = 4090;
261 @Property(name = "pwTransportVlan", intValue = PW_TRANSPORT_VLAN,
262 label = "vlan used for transport of pseudowires between switches")
263 private int pwTransportVlan = PW_TRANSPORT_VLAN;
264
Charles Chan03a73e02016-10-24 14:52:01 -0700265 ArpHandler arpHandler = null;
266 IcmpHandler icmpHandler = null;
267 IpHandler ipHandler = null;
268 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700269 ApplicationId appId;
270 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700271
Charles Chan03a73e02016-10-24 14:52:01 -0700272 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700273 private TunnelHandler tunnelHandler = null;
274 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700275 private InternalPacketProcessor processor = null;
276 private InternalLinkListener linkListener = null;
277 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700278 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100279 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800280 McastHandler mcastHandler = null;
281 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800282 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800283 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800284 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800285 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100286 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800287 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700288 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
289 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700290 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100291 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chana8487b02018-04-18 18:41:05 -0700292 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Dasc6dc1772018-04-21 17:19:48 -0700293 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanellaab482f92018-04-17 12:09:34 +0200294 //Completable future for network configuration process to buffer config events handling during activation
295 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chane437a802018-04-21 00:44:29 -0700296 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sanghob35a6192015-04-01 13:05:26 -0700297
Charles Chan9b7217c2018-04-05 16:31:15 -0700298 // Handles device, link, topology and network config events
Charles Chana8487b02018-04-18 18:41:05 -0700299 private ScheduledExecutorService mainEventExecutor;
sanghob35a6192015-04-01 13:05:26 -0700300
Charles Chana8487b02018-04-18 18:41:05 -0700301 // Handles host, route and mcast events respectively
302 private ScheduledExecutorService hostEventExecutor;
303 private ScheduledExecutorService routeEventExecutor;
304 private ScheduledExecutorService mcastEventExecutor;
Charles Chan595fdc52018-05-08 21:35:50 -0700305 private ExecutorService packetExecutor;
Charles Chan9b7217c2018-04-05 16:31:15 -0700306
307 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800308 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700309 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700310 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800311 */
Charles Chan47933752017-11-30 15:37:50 -0800312 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700313 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800314 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700315 * Per device next objective ID store with (device id + vlanid) as key.
316 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800317 */
Charles Chan47933752017-11-30 15:37:50 -0800318 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800319 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800320 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700321 * Per device next objective ID store with (device id + port + treatment + meta) as key.
322 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800323 */
Charles Chan47933752017-11-30 15:37:50 -0800324 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800325 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800326
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700327 /**
328 * Per port dummy VLAN ID store with (connect point + ip address) as key.
329 * Used to keep track on dummy VLAN ID allocation.
330 */
331 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
332 dummyVlanIdStore = null;
333
Saurav Das4ce45962015-11-24 23:21:05 -0800334 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
335 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700336
Saurav Das7bcbe702017-06-13 15:35:54 -0700337 private AtomicBoolean programmingScheduled = new AtomicBoolean();
338
Charles Chand55e84d2016-03-30 17:54:24 -0700339 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700340 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
341 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700342 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700343 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800344 public SegmentRoutingDeviceConfig createConfig() {
345 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700346 }
347 };
Pier Ventref34966c2016-11-07 16:21:04 -0800348
Charles Chand55e84d2016-03-30 17:54:24 -0700349 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700350 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
351 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700352 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800353 @Override
354 public SegmentRoutingAppConfig createConfig() {
355 return new SegmentRoutingAppConfig();
356 }
357 };
Pier Ventref34966c2016-11-07 16:21:04 -0800358
Charles Chanfc5c7802016-05-17 13:13:55 -0700359 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
360 new ConfigFactory<ApplicationId, XConnectConfig>(
361 SubjectFactories.APP_SUBJECT_FACTORY,
362 XConnectConfig.class, "xconnect") {
363 @Override
364 public XConnectConfig createConfig() {
365 return new XConnectConfig();
366 }
367 };
Pier Ventref34966c2016-11-07 16:21:04 -0800368
Charles Chand55e84d2016-03-30 17:54:24 -0700369 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700370 new ConfigFactory<ApplicationId, McastConfig>(
371 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700372 McastConfig.class, "multicast") {
373 @Override
374 public McastConfig createConfig() {
375 return new McastConfig();
376 }
377 };
378
Charles Chan116188d2016-02-18 14:22:42 -0800379 /**
380 * Segment Routing App ID.
381 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800382 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das0e99e2b2015-10-28 12:39:42 -0700383
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700384 /**
385 * Minumum and maximum value of dummy VLAN ID to be allocated.
386 */
387 public static final int MIN_DUMMY_VLAN_ID = 2;
388 public static final int MAX_DUMMY_VLAN_ID = 4093;
389
Saurav Das41b49a92018-04-27 18:42:30 -0700390 Instant lastEdgePortEvent = Instant.EPOCH;
391
sanghob35a6192015-04-01 13:05:26 -0700392 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800393 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800394 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700395
Charles Chana8487b02018-04-18 18:41:05 -0700396 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
397 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
398 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
399 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan595fdc52018-05-08 21:35:50 -0700400 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chana8487b02018-04-18 18:41:05 -0700401
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700402 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700403 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700404 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700405 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700406 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700407 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700408 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700409 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700410 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700411
Charles Chan59cc16d2017-02-02 16:20:42 -0800412 log.debug("Creating EC map vlannextobjectivestore");
413 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
414 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
415 vlanNextObjStore = vlanNextObjMapBuilder
416 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700417 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700418 .withTimestampProvider((k, v) -> new WallClockTimestamp())
419 .build();
420
Saurav Das4ce45962015-11-24 23:21:05 -0800421 log.debug("Creating EC map subnetnextobjectivestore");
422 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
423 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
424 portNextObjStore = portNextObjMapBuilder
425 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700426 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800427 .withTimestampProvider((k, v) -> new WallClockTimestamp())
428 .build();
429
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700430 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
431 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
432 dummyVlanIdStore = dummyVlanIdMapBuilder
433 .withName("dummyvlanidstore")
434 .withSerializer(createSerializer())
435 .withTimestampProvider((k, v) -> new WallClockTimestamp())
436 .build();
437
sangho0b2b6d12015-05-20 22:16:38 -0700438 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
439 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700440 tunnelStore = tunnelMapBuilder
441 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700442 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700443 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700444 .build();
445
446 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
447 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700448 policyStore = policyMapBuilder
449 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700450 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700451 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700452 .build();
453
Saurav Das80980c72016-03-23 11:22:49 -0700454 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800455 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700456 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800457 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800458 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
459 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700460 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800461 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700462 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800463 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800464 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
465 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800466 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
467 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700468 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700469 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700470 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
471 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800472 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
473 "staleLinkAge", "15000");
474 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
475 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800476 compCfgService.registerProperties(getClass());
477 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700478
Charles Chanb8e10c82015-10-14 11:24:40 -0700479 processor = new InternalPacketProcessor();
480 linkListener = new InternalLinkListener();
481 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700482 appCfgHandler = new AppConfigHandler(this);
483 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700484 mcastHandler = new McastHandler(this);
485 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800486 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700487 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800488 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800489 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100490 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700491
Charles Chan3e783d02016-02-26 22:19:52 -0800492 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700493 cfgService.registerConfigFactory(deviceConfigFactory);
494 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700495 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700496 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800497 log.info("Configuring network before adding listeners");
Andrea Campanellaab482f92018-04-17 12:09:34 +0200498
Charles Chan132393a2018-01-04 14:26:07 -0800499 cfgListener.configureNetwork();
500
Charles Chan5270ed02016-01-30 23:22:37 -0800501 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700502 packetService.addProcessor(processor, PacketProcessor.director(2));
503 linkService.addListener(linkListener);
504 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700505 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700506 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100507 topologyService.addListener(topologyListener);
Charles Chana8487b02018-04-18 18:41:05 -0700508 mastershipService.addListener(mastershipListener);
Saurav Dasc6dc1772018-04-21 17:19:48 -0700509 clusterService.addListener(clusterListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700510
Charles Chanb39777c2018-03-09 15:53:44 -0800511 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800512 l2TunnelHandler.init();
513
Andrea Campanellaab482f92018-04-17 12:09:34 +0200514 networkConfigCompletion.whenComplete((value, ex) -> {
515 //setting to null for easier fall through
516 networkConfigCompletion = null;
517 //process all queued events
Charles Chane437a802018-04-21 00:44:29 -0700518 queuedEvents.forEach(event -> {
Andrea Campanellaab482f92018-04-17 12:09:34 +0200519 mainEventExecutor.execute(new InternalEventHandler(event));
520 });
521 });
522
sanghob35a6192015-04-01 13:05:26 -0700523 log.info("Started");
524 }
525
Saurav Das45f48152018-01-18 12:07:33 -0800526 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700527 return new KryoNamespace.Builder()
528 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700529 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800530 VlanNextObjectiveStoreKey.class,
531 DestinationSet.class,
Andreas Pantelopoulos6c3ec952018-05-29 13:11:14 -0700532 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800533 NextNeighbors.class,
534 Tunnel.class,
535 DefaultTunnel.class,
536 Policy.class,
537 TunnelPolicy.class,
538 Policy.Type.class,
539 PortNextObjectiveStoreKey.class,
540 XConnectStoreKey.class,
541 L2Tunnel.class,
542 L2TunnelPolicy.class,
543 DefaultL2Tunnel.class,
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700544 DefaultL2TunnelPolicy.class,
545 DummyVlanIdStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700546 );
547 }
548
sanghob35a6192015-04-01 13:05:26 -0700549 @Deactivate
550 protected void deactivate() {
Charles Chana8487b02018-04-18 18:41:05 -0700551 mainEventExecutor.shutdown();
552 hostEventExecutor.shutdown();
553 routeEventExecutor.shutdown();
554 mcastEventExecutor.shutdown();
Charles Chan595fdc52018-05-08 21:35:50 -0700555 packetExecutor.shutdown();
Charles Chana8487b02018-04-18 18:41:05 -0700556
Ray Milkey59bc0722018-05-11 09:59:19 -0700557 mainEventExecutor = null;
558 hostEventExecutor = null;
559 routeEventExecutor = null;
560 mcastEventExecutor = null;
561 packetExecutor = null;
562
Charles Chand6832882015-10-05 17:50:33 -0700563 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700564 cfgService.unregisterConfigFactory(deviceConfigFactory);
565 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700566 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700567 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800568 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700569
Charles Chanc7a8a682017-06-19 00:43:31 -0700570 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700571 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700572 linkService.removeListener(linkListener);
573 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700574 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700575 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100576 topologyService.removeListener(topologyListener);
Charles Chana8487b02018-04-18 18:41:05 -0700577 mastershipService.removeListener(mastershipListener);
Saurav Dasc6dc1772018-04-21 17:19:48 -0700578 clusterService.removeListener(clusterListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700579
Charles Chan0aa674e2017-02-23 15:44:08 -0800580 neighbourResolutionService.unregisterNeighbourHandlers(appId);
581
sanghob35a6192015-04-01 13:05:26 -0700582 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700583 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700584 deviceListener = null;
Charles Chan5621b9e2018-04-19 13:10:01 -0700585 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chanb8e10c82015-10-14 11:24:40 -0700586 groupHandlerMap.clear();
Saurav Das60ca8d52018-04-23 18:42:12 -0700587 defaultRoutingHandler.shutdown();
Charles Chanb8e10c82015-10-14 11:24:40 -0700588
Saurav Das7bcbe702017-06-13 15:35:54 -0700589 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800590 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700591 portNextObjStore.destroy();
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700592 dummyVlanIdStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700593 tunnelStore.destroy();
594 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100595
596 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700597 log.info("Stopped");
598 }
599
Charles Chan47933752017-11-30 15:37:50 -0800600 @Modified
601 private void modified(ComponentContext context) {
602 Dictionary<?, ?> properties = context.getProperties();
603 if (properties == null) {
604 return;
605 }
606
Andreas Pantelopoulos7bf9e442018-06-18 12:50:35 -0700607 String strActiveProbing = Tools.get(properties, "activeProbing");
608 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan47933752017-11-30 15:37:50 -0800609 if (expectActiveProbing != activeProbing) {
610 activeProbing = expectActiveProbing;
611 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
612 }
Saurav Das41b49a92018-04-27 18:42:30 -0700613
614 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
615 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
616 if (expectSingleHomedDown != singleHomedDown) {
617 singleHomedDown = expectSingleHomedDown;
618 log.info("{} downing of single homed hosts for lost uplinks",
619 singleHomedDown ? "Enabling" : "Disabling");
620 if (singleHomedDown && linkHandler != null) {
621 hostService.getHosts().forEach(host -> host.locations()
622 .forEach(loc -> {
623 if (interfaceService.isConfigured(loc)) {
624 linkHandler.checkUplinksForHost(loc);
625 }
626 }));
627 } else {
628 log.warn("Disabling singleHomedDown does not re-enable already "
629 + "downed ports for single-homed hosts");
630 }
631 }
Andreas Pantelopoulos7bf9e442018-06-18 12:50:35 -0700632
633 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
634 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
635 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
636 respondToUnknownHosts = expectRespondToUnknownHosts;
637 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
638 }
Charles Chan3d44eb92018-07-19 14:55:31 -0700639
Charles Chan5b9a11a2018-07-24 16:40:35 -0700640 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
641 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
642 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
643 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
644 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan3d44eb92018-07-19 14:55:31 -0700645
Charles Chan5b9a11a2018-07-24 16:40:35 -0700646 if (routeDoubleTaggedHosts) {
Charles Chan3d44eb92018-07-19 14:55:31 -0700647 hostHandler.populateAllDoubleTaggedHost();
648 } else {
649 hostHandler.revokeAllDoubleTaggedHost();
650 }
651 }
Saurav Das3c82f192018-08-13 15:34:26 -0700652
653 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
654 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
655 if (defIntVlan != defaultInternalVlan) {
656 if (canUseVlanId(defIntVlan)) {
657 log.warn("Default internal vlan value changed from {} to {}.. "
658 + "re-programming filtering rules, but NOT any groups already "
659 + "created with the former value", defaultInternalVlan, defIntVlan);
660 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
661 defaultInternalVlan = defIntVlan;
662 routingRulePopulator
663 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
664 VlanId.vlanId((short) defIntVlan));
665 } else {
666 log.warn("Cannot change default internal vlan to unusable "
667 + "value {}", defIntVlan);
668 }
669 }
670
671 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
672 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
673 if (pwTxpVlan != pwTransportVlan) {
674 if (canUseVlanId(pwTxpVlan)) {
675 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
676 + "re-programming filtering rules, but NOT any groups already "
677 + "created with the former value", pwTransportVlan,
678 pwTxpVlan);
679 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
680 pwTransportVlan = pwTxpVlan;
681 routingRulePopulator
682 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
683 VlanId.vlanId((short) pwTxpVlan));
684 } else {
685 log.warn("Cannot change pseudowire transport vlan to unusable "
686 + "value {}", pwTxpVlan);
687 }
688 }
689
690 }
691
692 /**
693 * Returns true if given vlan id is not being used in the system currently,
694 * either as one of the default system wide vlans or as one of the
695 * configured interface vlans.
696 *
697 * @param vlanId given vlan id
698 * @return true if vlan is not currently in use
699 */
700 public boolean canUseVlanId(int vlanId) {
701 if (vlanId >= 4095 || vlanId <= 1) {
702 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
703 vlanId);
704 return false;
705 }
706
707 VlanId vid = VlanId.vlanId((short) vlanId);
708 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
709 log.warn("Vlan id {} value is already in use system-wide. "
710 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
711 getDefaultInternalVlan(), getPwTransportVlan());
712 return false;
713 }
714
715 if (interfaceService.inUse(vid)) {
716 log.warn("Vlan id {} value is already in use on a configured "
717 + "interface in the system", vlanId);
718 return false;
719 }
720 return true;
721 }
722
723 /**
724 * Returns the VlanId assigned internally by default to unconfigured ports.
725 *
726 * @return the default internal vlan id
727 */
728 public VlanId getDefaultInternalVlan() {
729 return VlanId.vlanId((short) defaultInternalVlan);
730 }
731
732 /**
733 * Returns the Vlan id used to transport pseudowire traffic across the
734 * network.
735 *
736 * @return the pseudowire transport vlan id
737 */
738 public VlanId getPwTransportVlan() {
739 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan47933752017-11-30 15:37:50 -0800740 }
741
sangho1e575652015-05-14 00:39:53 -0700742 @Override
743 public List<Tunnel> getTunnels() {
744 return tunnelHandler.getTunnels();
745 }
746
747 @Override
sangho71abe1b2015-06-29 14:58:47 -0700748 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
749 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700750 }
751
752 @Override
sangho71abe1b2015-06-29 14:58:47 -0700753 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700754 for (Policy policy: policyHandler.getPolicies()) {
755 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
756 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
757 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
758 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700759 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700760 }
761 }
762 }
sangho71abe1b2015-06-29 14:58:47 -0700763 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700764 }
765
766 @Override
sangho71abe1b2015-06-29 14:58:47 -0700767 public PolicyHandler.Result removePolicy(Policy policy) {
768 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700769 }
770
771 @Override
sangho71abe1b2015-06-29 14:58:47 -0700772 public PolicyHandler.Result createPolicy(Policy policy) {
773 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700774 }
775
776 @Override
777 public List<Policy> getPolicies() {
778 return policyHandler.getPolicies();
779 }
780
Saurav Das59232cf2016-04-27 18:35:50 -0700781 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700782 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
783 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700784 }
785
786 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800787 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700788 return l2TunnelHandler.getL2Tunnels();
789 }
790
791 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800792 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700793 return l2TunnelHandler.getL2Policies();
794 }
795
Saurav Das5a356042018-04-06 20:16:01 -0700796 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700797 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700798 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
799
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700800 // get both added and pending pseudowires
801 List<L2TunnelDescription> pseudowires = new ArrayList<>();
802 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
803 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700804 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700805
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700806 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
807
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700808 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
809 L2TunnelHandler.Result res;
810 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
811 res = addPseudowire(pw);
812 if (res != L2TunnelHandler.Result.SUCCESS) {
813 log.error("Pseudowire with id {} can not be instantiated !", res);
814 retRes = res;
815 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700816 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700817
818 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700819 }
820
821 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800822 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700823 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700824 }
825
826 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800827 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700828 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700829 }
830
831 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700832 public void rerouteNetwork() {
833 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700834 }
835
Charles Chanc81c45b2016-10-20 17:02:44 -0700836 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800837 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
838 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800839 deviceConfiguration.getRouters().forEach(device ->
840 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700841 return deviceSubnetMap;
842 }
843
Saurav Dasc88d4662017-05-15 15:34:25 -0700844
845 @Override
846 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
847 if (defaultRoutingHandler != null) {
848 return defaultRoutingHandler.getCurrentEmcpSpgMap();
849 } else {
850 return null;
851 }
852 }
853
854 @Override
Charles Chan1fa010c2018-08-19 19:21:46 -0700855 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das7bcbe702017-06-13 15:35:54 -0700856 if (dsNextObjStore != null) {
857 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700858 } else {
859 return ImmutableMap.of();
860 }
861 }
862
Saurav Dasceccf242017-08-03 18:30:35 -0700863 @Override
Charles Chan1fa010c2018-08-19 19:21:46 -0700864 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
865 if (vlanNextObjStore != null) {
866 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
867 } else {
868 return ImmutableMap.of();
869 }
870 }
871
872 @Override
873 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
874 if (portNextObjStore != null) {
875 return ImmutableMap.copyOf(portNextObjStore.entrySet());
876 } else {
877 return ImmutableMap.of();
878 }
879 }
880
881 @Override
882 public ImmutableMap<String, NextObjective> getPwInitNext() {
883 if (l2TunnelHandler != null) {
884 return l2TunnelHandler.getInitNext();
885 } else {
886 return ImmutableMap.of();
887 }
888 }
889
890 @Override
891 public ImmutableMap<String, NextObjective> getPwTermNext() {
892 if (l2TunnelHandler != null) {
893 return l2TunnelHandler.getTermNext();
894 } else {
895 return ImmutableMap.of();
896 }
897 }
898
899 @Override
900 public void invalidateNextObj(int nextId) {
901 if (dsNextObjStore != null) {
902 dsNextObjStore.entrySet().forEach(e -> {
903 if (e.getValue().nextId() == nextId) {
904 dsNextObjStore.remove(e.getKey());
905 }
906 });
907 }
908 if (vlanNextObjStore != null) {
909 vlanNextObjStore.entrySet().forEach(e -> {
910 if (e.getValue() == nextId) {
911 vlanNextObjStore.remove(e.getKey());
912 }
913 });
914 }
915 if (portNextObjStore != null) {
916 portNextObjStore.entrySet().forEach(e -> {
917 if (e.getValue() == nextId) {
918 portNextObjStore.remove(e.getKey());
919 }
920 });
921 }
922 if (mcastHandler != null) {
923 mcastHandler.removeNextId(nextId);
924 }
925 if (l2TunnelHandler != null) {
926 l2TunnelHandler.removeNextId(nextId);
927 }
928 if (xconnectService != null) {
929 xconnectService.removeNextId(nextId);
930 }
931 }
932
933 @Override
Saurav Dasceccf242017-08-03 18:30:35 -0700934 public void verifyGroups(DeviceId id) {
935 DefaultGroupHandler gh = groupHandlerMap.get(id);
936 if (gh != null) {
937 gh.triggerBucketCorrector();
938 }
939 }
940
Saurav Dasc568c342018-01-25 09:49:01 -0800941 @Override
942 public ImmutableMap<Link, Boolean> getSeenLinks() {
943 return linkHandler.getSeenLinks();
944 }
945
946 @Override
947 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
948 return linkHandler.getDownedPorts();
949 }
950
Pier Luigib29144d2018-01-15 18:06:43 +0100951 @Override
952 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan1fa010c2018-08-19 19:21:46 -0700953 return mcastHandler.getNextIds(mcastIp);
Pier Luigib29144d2018-01-15 18:06:43 +0100954 }
955
956 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100957 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100958 return mcastHandler.getMcastRoles(mcastIp);
959 }
960
961 @Override
Pier7631c492018-04-19 16:47:06 +0200962 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
963 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
964 }
965
966 @Override
Pier Luigib29144d2018-01-15 18:06:43 +0100967 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
968 return mcastHandler.getMcastPaths(mcastIp);
969 }
970
Pier4694e092018-04-17 16:29:56 +0200971 @Override
Piere7e8e3c2018-04-17 17:25:22 +0200972 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
973 ConnectPoint sourcecp) {
974 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
975 }
976
977 @Override
Pier4694e092018-04-17 16:29:56 +0200978 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
979 return mcastHandler.getMcastLeaders(mcastIp);
980 }
981
Charles Chan09879082018-04-17 18:56:53 -0700982 @Override
983 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
984 return defaultRoutingHandler == null ? ImmutableMap.of() :
985 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
986 }
987
988 @Override
989 public Map<DeviceId, Boolean> getShouldProgramCache() {
990 return defaultRoutingHandler == null ? ImmutableMap.of() :
991 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
992 }
993
Charles Chan4e87b3e2018-06-19 20:31:57 -0700994 @Override
Ray Milkeye4afdb52017-04-05 09:42:04 -0700995 public ApplicationId appId() {
996 return appId;
997 }
998
999 /**
1000 * Returns the device configuration.
1001 *
1002 * @return device configuration
1003 */
1004 public DeviceConfiguration deviceConfiguration() {
1005 return deviceConfiguration;
1006 }
1007
1008 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001009 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -07001010 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001011 *
1012 * @return next objective ID store
1013 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001014 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1015 dsNextObjStore() {
1016 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -07001017 }
1018
1019 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001020 * Per device next objective ID store with (device id + vlanid) as key.
1021 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001022 *
1023 * @return vlan next object store
1024 */
1025 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1026 return vlanNextObjStore;
1027 }
1028
1029 /**
Charles Chan5bc32632017-08-22 15:07:34 -07001030 * Per device next objective ID store with (device id + port + treatment + meta) as key.
1031 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -07001032 *
1033 * @return port next object store.
1034 */
1035 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1036 return portNextObjStore;
1037 }
1038
1039 /**
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001040 * Per port dummy VLAN ID store with (connect point + ip address) as key.
1041 * Used to keep track on dummy VLAN ID allocation.
1042 *
1043 * @return dummy vlan id store.
1044 */
1045 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
1046 return dummyVlanIdStore;
1047 }
1048
1049 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001050 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1051 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -07001052 *
1053 * @return MPLS-ECMP value
1054 */
1055 public boolean getMplsEcmp() {
1056 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1057 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1058 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1059 }
1060
1061 /**
sanghof9d0bf12015-05-19 11:57:42 -07001062 * Returns the tunnel object with the tunnel ID.
1063 *
1064 * @param tunnelId Tunnel ID
1065 * @return Tunnel reference
1066 */
sangho1e575652015-05-14 00:39:53 -07001067 public Tunnel getTunnel(String tunnelId) {
1068 return tunnelHandler.getTunnel(tunnelId);
1069 }
1070
Charles Chan4e87b3e2018-06-19 20:31:57 -07001071 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +01001072 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanb30213c2018-05-01 11:50:20 -07001073 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1074 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -07001075 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1076 }
1077
Charles Chan4e87b3e2018-06-19 20:31:57 -07001078 @Override
1079 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001080 SegmentRoutingDeviceConfig deviceConfig =
1081 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1082 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1083 }
Charles Chan4e87b3e2018-06-19 20:31:57 -07001084
1085 @Override
Saurav Das41b49a92018-04-27 18:42:30 -07001086 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -07001087 SegmentRoutingDeviceConfig deviceConfig =
1088 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1089 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1090 }
1091
1092 /**
Charles Chan9640c812017-08-23 13:55:39 -07001093 * Returns locations of given resolved route.
1094 *
1095 * @param resolvedRoute resolved route
1096 * @return locations of nexthop. Might be empty if next hop is not found
1097 */
1098 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1099 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1100 return Optional.ofNullable(hostService.getHost(hostId))
1101 .map(Host::locations).orElse(Sets.newHashSet())
1102 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1103 }
1104
1105 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -08001106 * Returns vlan port map of given device.
1107 *
1108 * @param deviceId device id
1109 * @return vlan-port multimap
1110 */
1111 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1112 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1113
1114 interfaceService.getInterfaces().stream()
1115 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1116 .forEach(intf -> {
1117 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -07001118 intf.vlanTagged().forEach(vlanTagged ->
1119 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1120 );
Charles Chan7ffd81f2017-02-08 15:52:08 -08001121 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1122 });
1123 vlanPortMap.removeAll(VlanId.NONE);
1124
1125 return vlanPortMap;
1126 }
1127
1128 /**
Charles Chan59cc16d2017-02-02 16:20:42 -08001129 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -08001130 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -07001131 *
1132 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -08001133 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -08001134 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -07001135 */
Charles Chan65238242017-06-22 18:03:14 -07001136 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -07001137 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -08001138 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1139 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001140 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -08001141 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -08001142 + "device {} not found", deviceId);
1143 return -1;
1144 }
1145 }
1146
1147 /**
1148 * Returns the next objective ID for the given portNumber, given the treatment.
1149 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -07001150 * would result in different objectives. If the next object does not exist,
1151 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -08001152 *
1153 * @param deviceId Device ID
1154 * @param portNum port number on device for which NextObjective is queried
1155 * @param treatment the actions to apply on the packets (should include outport)
1156 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -07001157 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -07001158 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -08001159 */
1160 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1161 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -07001162 TrafficSelector meta,
1163 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -08001164 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1165 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -07001166 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -08001167 } else {
Charles Chane849c192016-01-11 18:28:54 -08001168 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1169 + " not found", deviceId);
1170 return -1;
1171 }
1172 }
1173
Saurav Dasc88d4662017-05-15 15:34:25 -07001174 /**
1175 * Returns the group handler object for the specified device id.
1176 *
1177 * @param devId the device identifier
1178 * @return the groupHandler object for the device id, or null if not found
1179 */
Charles Chan65238242017-06-22 18:03:14 -07001180 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001181 return groupHandlerMap.get(devId);
1182 }
1183
1184 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001185 * Returns the default routing handler object.
1186 *
1187 * @return the default routing handler object
1188 */
1189 public DefaultRoutingHandler getRoutingHandler() {
1190 return defaultRoutingHandler;
1191 }
1192
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001193 /**
1194 * Returns new dummy VLAN ID.
1195 * Dummy VLAN ID should be unique in each connect point.
1196 *
1197 * @param cp connect point
1198 * @param ipAddress IP address
1199 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1200 */
1201 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1202 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1203 dummyVlanIdStore.entrySet().stream().filter(entry ->
1204 (entry.getKey()).connectPoint().equals(cp))
1205 .map(Map.Entry::getValue)
1206 .collect(Collectors.toSet()));
1207
1208 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1209 i -> VlanId.vlanId((short) (i & 0xFFFF))
1210 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1211
1212 if (!dummyVlanId.equals(VlanId.NONE)) {
1213 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1214 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1215 } else {
1216 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1217 }
1218 return dummyVlanId;
1219 }
1220
1221
sanghob35a6192015-04-01 13:05:26 -07001222 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001223 @Override
1224 public void process(PacketContext context) {
Charles Chan595fdc52018-05-08 21:35:50 -07001225 packetExecutor.execute(() -> processPacketInternal(context));
1226 }
sanghob35a6192015-04-01 13:05:26 -07001227
Charles Chan595fdc52018-05-08 21:35:50 -07001228 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001229 if (context.isHandled()) {
1230 return;
1231 }
1232
1233 InboundPacket pkt = context.inPacket();
1234 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001235
1236 if (ethernet == null) {
1237 return;
1238 }
1239
Saurav Das7bcbe702017-06-13 15:35:54 -07001240 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1241 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001242 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001243 log.warn("Received unexpected ARP packet on {}",
1244 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001245 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001246 return;
sanghob35a6192015-04-01 13:05:26 -07001247 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001248 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1249 //ipHandler.addToPacketBuffer(ipv4Packet);
1250 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1251 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001252 } else {
Charles Chan50035632017-01-13 17:20:44 -08001253 // NOTE: We don't support IP learning at this moment so this
1254 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001255 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001256 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001257 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1258 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001259 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001260 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001261 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1262 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1263 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1264 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1265 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1266 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001267 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001268 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001269 }
1270 } else {
1271 // NOTE: We don't support IP learning at this moment so this
1272 // is not necessary. Also it causes duplication of DHCPv6 packets.
1273 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1274 }
sanghob35a6192015-04-01 13:05:26 -07001275 }
1276 }
1277 }
1278
sanghob35a6192015-04-01 13:05:26 -07001279 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001280 private Event event;
1281
1282 InternalEventHandler(Event event) {
1283 this.event = event;
1284 }
1285
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001286 @Override
sanghob35a6192015-04-01 13:05:26 -07001287 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001288 try {
1289 // TODO We should also change SR routing and PW to listen to TopologyEvents
1290 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1291 event.type() == LinkEvent.Type.LINK_UPDATED) {
1292 linkHandler.processLinkAdded((Link) event.subject());
1293 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1294 linkHandler.processLinkRemoved((Link) event.subject());
1295 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1296 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1297 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1298 DeviceId deviceId = ((Device) event.subject()).id();
1299 if (deviceService.isAvailable(deviceId)) {
1300 log.info("** DEVICE UP Processing device event {} "
1301 + "for available device {}",
1302 event.type(), ((Device) event.subject()).id());
1303 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001304 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001305 log.info(" ** DEVICE DOWN Processing device event {}"
1306 + " for unavailable device {}",
1307 event.type(), ((Device) event.subject()).id());
1308 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001309 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001310 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1311 // typically these calls come when device is added first time
1312 // so port filtering rules are handled at the device_added event.
1313 // port added calls represent all ports on the device,
1314 // enabled or not.
1315 log.trace("** PORT ADDED {}/{} -> {}",
1316 ((DeviceEvent) event).subject().id(),
1317 ((DeviceEvent) event).port().number(),
1318 event.type());
1319 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1320 // these calls happen for every subsequent event
1321 // ports enabled, disabled, switch goes away, comes back
1322 log.info("** PORT UPDATED {}/{} -> {}",
1323 event.subject(),
1324 ((DeviceEvent) event).port(),
1325 event.type());
Saurav Das41b49a92018-04-27 18:42:30 -07001326 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001327 ((DeviceEvent) event).port());
1328 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1329 // Process topology event, needed for all modules relying on
1330 // topology service for path computation
1331 TopologyEvent topologyEvent = (TopologyEvent) event;
1332 log.info("Processing topology event {}, topology age {}, reasons {}",
1333 event.type(), topologyEvent.subject().time(),
1334 topologyEvent.reasons().size());
1335 topologyHandler.processTopologyChange(topologyEvent.reasons());
1336 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1337 hostHandler.processHostAddedEvent((HostEvent) event);
1338 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1339 hostHandler.processHostMovedEvent((HostEvent) event);
1340 routeHandler.processHostMovedEvent((HostEvent) event);
1341 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1342 hostHandler.processHostRemovedEvent((HostEvent) event);
1343 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1344 hostHandler.processHostUpdatedEvent((HostEvent) event);
1345 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1346 routeHandler.processRouteAdded((RouteEvent) event);
1347 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1348 routeHandler.processRouteUpdated((RouteEvent) event);
1349 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1350 routeHandler.processRouteRemoved((RouteEvent) event);
1351 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1352 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1353 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1354 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1355 event.type() == McastEvent.Type.SINKS_ADDED ||
1356 event.type() == McastEvent.Type.SINKS_REMOVED ||
1357 event.type() == McastEvent.Type.ROUTE_ADDED ||
1358 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1359 mcastHandler.processMcastEvent((McastEvent) event);
1360 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1361 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1362 Class configClass = netcfgEvent.configClass();
1363 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1364 appCfgHandler.processAppConfigAdded(netcfgEvent);
1365 log.info("App config event .. configuring network");
1366 cfgListener.configureNetwork();
1367 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1368 log.info("Segment Routing Device Config added for {}", event.subject());
1369 cfgListener.configureNetwork();
1370 } else if (configClass.equals(XConnectConfig.class)) {
1371 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1372 } else if (configClass.equals(InterfaceConfig.class)) {
1373 log.info("Interface Config added for {}", event.subject());
1374 cfgListener.configureNetwork();
1375 } else {
1376 log.error("Unhandled config class: {}", configClass);
1377 }
1378 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1379 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1380 Class configClass = netcfgEvent.configClass();
1381 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1382 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1383 log.info("App config event .. configuring network");
1384 cfgListener.configureNetwork();
1385 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1386 log.info("Segment Routing Device Config updated for {}", event.subject());
1387 createOrUpdateDeviceConfiguration();
1388 } else if (configClass.equals(XConnectConfig.class)) {
1389 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1390 } else if (configClass.equals(InterfaceConfig.class)) {
1391 log.info("Interface Config updated for {}", event.subject());
1392 createOrUpdateDeviceConfiguration();
1393 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1394 (InterfaceConfig) netcfgEvent.prevConfig().get());
1395 } else {
1396 log.error("Unhandled config class: {}", configClass);
1397 }
1398 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1399 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1400 Class configClass = netcfgEvent.configClass();
1401 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1402 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1403 log.info("App config event .. configuring network");
1404 cfgListener.configureNetwork();
1405 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1406 // TODO Handle sr device config removal
1407 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1408 } else if (configClass.equals(XConnectConfig.class)) {
1409 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1410 } else if (configClass.equals(InterfaceConfig.class)) {
1411 // TODO Handle interface removal
1412 log.info("InterfaceConfig removal is not handled in current implementation");
1413 } else {
1414 log.error("Unhandled config class: {}", configClass);
1415 }
Saurav Dasc6dc1772018-04-21 17:19:48 -07001416 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1417 MastershipEvent me = (MastershipEvent) event;
1418 DeviceId deviceId = me.subject();
1419 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1420 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1421 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1422 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1423 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1424 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001425 } else {
1426 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001427 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001428 } catch (Exception e) {
1429 log.error("SegmentRouting event handler thread thrown an exception: {}",
1430 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001431 }
sanghob35a6192015-04-01 13:05:26 -07001432 }
1433 }
1434
Saurav Das45f48152018-01-18 12:07:33 -08001435 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001436 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001437
1438 // NOTE: Punt ARP/NDP even when the device is not configured.
1439 // Host learning without network config is required for CORD config generator.
1440 routingRulePopulator.populateIpPunts(device.id());
1441 routingRulePopulator.populateArpNdpPunts(device.id());
1442
Charles Chan0b4e6182015-11-03 10:42:14 -08001443 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001444 log.warn("Device configuration unavailable. Device {} will be "
1445 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001446 return;
1447 }
Charles Chan2199c302016-04-23 17:36:10 -07001448 processDeviceAddedInternal(device.id());
1449 }
1450
1451 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001452 // Irrespective of whether the local is a MASTER or not for this device,
1453 // we need to create a SR-group-handler instance. This is because in a
1454 // multi-instance setup, any instance can initiate forwarding/next-objectives
1455 // for any switch (even if this instance is a SLAVE or not even connected
1456 // to the switch). To handle this, a default-group-handler instance is necessary
1457 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001458 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1459 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001460 DefaultGroupHandler groupHandler;
1461 try {
1462 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001463 createGroupHandler(deviceId,
1464 appId,
1465 deviceConfiguration,
1466 linkService,
1467 flowObjectiveService,
1468 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001469 } catch (DeviceConfigNotFoundException e) {
1470 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1471 return;
1472 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001473 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001474 deviceId);
1475 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001476 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001477
Charles Chan2199c302016-04-23 17:36:10 -07001478 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001479 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001480 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001481 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001482 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001483 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001484 }
Charles Chan5270ed02016-01-30 23:22:37 -08001485
Charles Chan03a73e02016-10-24 14:52:01 -07001486 appCfgHandler.init(deviceId);
Charles Chana03ab8b2018-04-29 18:11:37 -07001487 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1488 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001489 }
1490
Saurav Das80980c72016-03-23 11:22:49 -07001491 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001492 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001493 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001494 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001495 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001496 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001497 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001498 portNextObjStore.entrySet().stream()
1499 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001500 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001501 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001502
Saurav Dasceccf242017-08-03 18:30:35 -07001503 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1504 if (gh != null) {
1505 gh.shutdown();
1506 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001507 // Note that a switch going down is associated with all of its links
1508 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001509 // while the link-downs are ignored. We cannot rely on the ordering of
1510 // events - i.e we cannot expect all link-downs to come before the
1511 // switch down - so we purge all seen-links for the switch before
1512 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001513 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001514 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001515 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001516 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001517
1518 // Cleanup all internal groupHandler stores for this device. Should be
1519 // done after all rerouting or rehashing has been completed
1520 groupHandlerMap.entrySet()
1521 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001522 }
1523
Saurav Das60ca8d52018-04-23 18:42:12 -07001524 /**
1525 * Purge the destinationSet nextObjective store of entries with this device
1526 * as key. Erases app-level knowledge of hashed groups in this device.
1527 *
1528 * @param devId the device identifier
1529 */
Saurav Dasc6dc1772018-04-21 17:19:48 -07001530 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das60ca8d52018-04-23 18:42:12 -07001531 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Dasc6dc1772018-04-21 17:19:48 -07001532 dsNextObjStore.entrySet().stream()
1533 .filter(entry -> entry.getKey().deviceId().equals(devId))
1534 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1535 }
1536
Saurav Das41b49a92018-04-27 18:42:30 -07001537 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001538 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1539 log.warn("Device configuration uploading. Not handling port event for"
1540 + "dev: {} port: {}", device.id(), port.number());
1541 return;
1542 }
Saurav Das018605f2017-02-18 14:05:44 -08001543
Saurav Das41b49a92018-04-27 18:42:30 -07001544 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1545 lastEdgePortEvent = Instant.now();
1546 }
1547
Saurav Das018605f2017-02-18 14:05:44 -08001548 if (!mastershipService.isLocalMaster(device.id())) {
1549 log.debug("Not master for dev:{} .. not handling port updated event"
1550 + "for port {}", device.id(), port.number());
1551 return;
1552 }
Saurav Das41b49a92018-04-27 18:42:30 -07001553 processPortUpdated(device.id(), port);
1554 }
Saurav Das018605f2017-02-18 14:05:44 -08001555
Saurav Das41b49a92018-04-27 18:42:30 -07001556 /**
1557 * Adds or remove filtering rules for the given switchport. If switchport is
1558 * an edge facing port, additionally handles host probing and broadcast
1559 * rules. Must be called by local master of device.
1560 *
1561 * @param deviceId the device identifier
1562 * @param port the port to update
1563 */
1564 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001565 // first we handle filtering rules associated with the port
1566 if (port.isEnabled()) {
1567 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das41b49a92018-04-27 18:42:30 -07001568 deviceId, port.number());
1569 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001570 } else {
1571 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das41b49a92018-04-27 18:42:30 -07001572 deviceId, port.number());
1573 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001574 }
Saurav Das1a129a02016-11-18 15:21:57 -08001575
1576 // portUpdated calls are for ports that have gone down or up. For switch
1577 // to switch ports, link-events should take care of any re-routing or
1578 // group editing necessary for port up/down. Here we only process edge ports
1579 // that are already configured.
Saurav Das41b49a92018-04-27 18:42:30 -07001580 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chanb30213c2018-05-01 11:50:20 -07001581 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1582 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1583 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001584
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001585 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001586 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das41b49a92018-04-27 18:42:30 -07001587 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001588 return;
1589 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001590 if (untaggedVlan != null) {
Saurav Das41b49a92018-04-27 18:42:30 -07001591 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001592 }
1593 if (nativeVlan != null) {
Saurav Das41b49a92018-04-27 18:42:30 -07001594 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001595 }
1596 if (!taggedVlans.isEmpty()) {
Saurav Das41b49a92018-04-27 18:42:30 -07001597 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001598 }
Saurav Das1a129a02016-11-18 15:21:57 -08001599 }
1600
Saurav Das41b49a92018-04-27 18:42:30 -07001601 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001602 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001603 boolean portUp = port.isEnabled();
1604 if (portUp) {
Saurav Das41b49a92018-04-27 18:42:30 -07001605 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001606 port.number(), vlanId);
Charles Chana03ab8b2018-04-29 18:11:37 -07001607 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001608 } else {
Saurav Das41b49a92018-04-27 18:42:30 -07001609 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001610 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001611 }
1612
Saurav Das41b49a92018-04-27 18:42:30 -07001613 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001614 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001615 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001616 } else {
1617 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das41b49a92018-04-27 18:42:30 -07001618 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001619 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001620 }
1621 }
sangho1e575652015-05-14 00:39:53 -07001622
Charles Chan27fe1a52017-10-20 16:06:55 -07001623 private void createOrUpdateDeviceConfiguration() {
1624 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001625 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001626 deviceConfiguration = new DeviceConfiguration(this);
1627 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001628 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001629 deviceConfiguration.updateConfig();
1630 }
1631 }
1632
Charles Chana8487b02018-04-18 18:41:05 -07001633 private void createOrUpdateDefaultRoutingHandler() {
1634 if (defaultRoutingHandler == null) {
1635 log.info("Creating new DefaultRoutingHandler");
1636 defaultRoutingHandler = new DefaultRoutingHandler(this);
1637 } else {
1638 log.info("Updating DefaultRoutingHandler");
1639 defaultRoutingHandler.update(this);
1640 }
1641 }
1642
Pier Ventre10bd8d12016-11-26 21:05:22 -08001643 /**
1644 * Registers the given connect point with the NRS, this is necessary
1645 * to receive the NDP and ARP packets from the NRS.
1646 *
1647 * @param portToRegister connect point to register
1648 */
1649 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001650 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001651 portToRegister,
1652 neighbourHandler,
1653 appId
1654 );
1655 }
1656
Charles Chand6832882015-10-05 17:50:33 -07001657 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001658 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001659 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001660
Charles Chane849c192016-01-11 18:28:54 -08001661 /**
1662 * Constructs the internal network config listener.
1663 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001664 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001665 */
Charles Chan65238242017-06-22 18:03:14 -07001666 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001667 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001668 }
1669
Charles Chane849c192016-01-11 18:28:54 -08001670 /**
1671 * Reads network config and initializes related data structure accordingly.
1672 */
Charles Chan47933752017-11-30 15:37:50 -08001673 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001674 log.info("Configuring network ...");
Andrea Campanellaab482f92018-04-17 12:09:34 +02001675
1676 // Setting handling of network configuration events completable future
1677 // The completable future is needed because of the async behaviour of the configureNetwork,
1678 // listener registration and event arrival
1679 // Enables us to buffer the events and execute them when the configure network is done.
1680 networkConfigCompletion = new CompletableFuture<>();
1681
1682 // add a small delay to absorb multiple network config added notifications
1683 if (!programmingScheduled.get()) {
1684 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1685 programmingScheduled.set(true);
1686 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1687 }
1688
Charles Chan27fe1a52017-10-20 16:06:55 -07001689 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001690
Charles Chan2c15aca2016-11-09 20:51:44 -08001691 arpHandler = new ArpHandler(srManager);
1692 icmpHandler = new IcmpHandler(srManager);
1693 ipHandler = new IpHandler(srManager);
1694 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chana8487b02018-04-18 18:41:05 -07001695 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001696
1697 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1698 groupHandlerMap, tunnelStore);
1699 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1700 flowObjectiveService,
1701 tunnelHandler, policyStore);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001702 networkConfigCompletion.complete(true);
1703
Charles Chan2199c302016-04-23 17:36:10 -07001704 mcastHandler.init();
Andrea Campanellaab482f92018-04-17 12:09:34 +02001705
Charles Chan4636be02015-10-07 14:21:45 -07001706 }
1707
Charles Chand6832882015-10-05 17:50:33 -07001708 @Override
1709 public void event(NetworkConfigEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001710 if (mainEventExecutor == null) {
1711 return;
1712 }
Charles Chan7a888e82018-03-21 16:57:47 -07001713 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1714 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1715 switch (event.type()) {
1716 case CONFIG_ADDED:
1717 case CONFIG_UPDATED:
1718 case CONFIG_REMOVED:
1719 log.trace("Schedule Network Config event {}", event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001720 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1721 mainEventExecutor.execute(new InternalEventHandler(event));
1722 } else {
Charles Chane437a802018-04-21 00:44:29 -07001723 queuedEvents.add(event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001724 }
Charles Chan7a888e82018-03-21 16:57:47 -07001725 break;
1726 default:
1727 break;
Charles Chand6832882015-10-05 17:50:33 -07001728 }
1729 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001730
Charles Chan50443e82018-01-03 16:26:32 -08001731 @Override
1732 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001733 if (event.type() == CONFIG_REGISTERED ||
1734 event.type() == CONFIG_UNREGISTERED) {
1735 log.debug("Ignore event {} due to type mismatch", event);
1736 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001737 }
Saurav Dase7f51012018-02-09 17:26:45 -08001738
1739 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1740 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1741 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001742 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001743 log.debug("Ignore event {} due to class mismatch", event);
1744 return false;
1745 }
1746
1747 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001748 }
1749
Saurav Das7bcbe702017-06-13 15:35:54 -07001750 private final class ConfigChange implements Runnable {
1751 @Override
1752 public void run() {
1753 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001754 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001755 for (Device device : deviceService.getDevices()) {
1756 processDeviceAdded(device);
1757 }
1758 defaultRoutingHandler.startPopulationProcess();
1759 }
1760 }
Charles Chand6832882015-10-05 17:50:33 -07001761 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001762
Charles Chan7a888e82018-03-21 16:57:47 -07001763 private class InternalLinkListener implements LinkListener {
1764 @Override
1765 public void event(LinkEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001766 if (mainEventExecutor == null) {
1767 return;
1768 }
Charles Chan7a888e82018-03-21 16:57:47 -07001769 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1770 event.type() == LinkEvent.Type.LINK_UPDATED ||
1771 event.type() == LinkEvent.Type.LINK_REMOVED) {
1772 log.trace("Schedule Link event {}", event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001773 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1774 mainEventExecutor.execute(new InternalEventHandler(event));
1775 } else {
Charles Chane437a802018-04-21 00:44:29 -07001776 queuedEvents.add(event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001777 }
Charles Chan7a888e82018-03-21 16:57:47 -07001778 }
1779 }
1780 }
1781
1782 private class InternalDeviceListener implements DeviceListener {
1783 @Override
1784 public void event(DeviceEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001785 if (mainEventExecutor == null) {
1786 return;
1787 }
Charles Chan7a888e82018-03-21 16:57:47 -07001788 switch (event.type()) {
1789 case DEVICE_ADDED:
1790 case PORT_UPDATED:
1791 case PORT_ADDED:
1792 case DEVICE_UPDATED:
1793 case DEVICE_AVAILABILITY_CHANGED:
1794 log.trace("Schedule Device event {}", event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001795 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1796 mainEventExecutor.execute(new InternalEventHandler(event));
1797 } else {
Charles Chane437a802018-04-21 00:44:29 -07001798 queuedEvents.add(event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001799 }
Charles Chan7a888e82018-03-21 16:57:47 -07001800 break;
1801 default:
1802 }
1803 }
1804 }
1805
1806 private class InternalTopologyListener implements TopologyListener {
1807 @Override
1808 public void event(TopologyEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001809 if (mainEventExecutor == null) {
1810 return;
1811 }
Charles Chan7a888e82018-03-21 16:57:47 -07001812 switch (event.type()) {
1813 case TOPOLOGY_CHANGED:
1814 log.trace("Schedule Topology event {}", event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001815 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1816 mainEventExecutor.execute(new InternalEventHandler(event));
1817 } else {
Charles Chane437a802018-04-21 00:44:29 -07001818 queuedEvents.add(event);
Andrea Campanellaab482f92018-04-17 12:09:34 +02001819 }
Charles Chan7a888e82018-03-21 16:57:47 -07001820 break;
1821 default:
1822 }
1823 }
1824 }
1825
Charles Chan68aa62d2015-11-09 16:37:23 -08001826 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001827 @Override
1828 public void event(HostEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001829 if (hostEventExecutor == null) {
1830 return;
1831 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001832 switch (event.type()) {
1833 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001834 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001835 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001836 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001837 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001838 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001839 break;
1840 default:
1841 log.warn("Unsupported host event type: {}", event.type());
1842 break;
1843 }
1844 }
1845 }
1846
Charles Chand55e84d2016-03-30 17:54:24 -07001847 private class InternalMcastListener implements McastListener {
1848 @Override
1849 public void event(McastEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001850 if (mcastEventExecutor == null) {
1851 return;
1852 }
Charles Chand55e84d2016-03-30 17:54:24 -07001853 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001854 case SOURCES_ADDED:
1855 case SOURCES_REMOVED:
1856 case SINKS_ADDED:
1857 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001858 case ROUTE_REMOVED:
Pier4694e092018-04-17 16:29:56 +02001859 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001860 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001861 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001862 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001863 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001864 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001865 break;
1866 }
1867 }
1868 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001869
Charles Chan03a73e02016-10-24 14:52:01 -07001870 private class InternalRouteEventListener implements RouteListener {
1871 @Override
1872 public void event(RouteEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001873 if (routeEventExecutor == null) {
1874 return;
1875 }
Charles Chan03a73e02016-10-24 14:52:01 -07001876 switch (event.type()) {
1877 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001878 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001879 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001880 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001881 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001882 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001883 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001884 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001885 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001886 break;
1887 }
1888 }
1889 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001890
Charles Chana8487b02018-04-18 18:41:05 -07001891 private class InternalMastershipListener implements MastershipListener {
1892 @Override
1893 public void event(MastershipEvent event) {
Ray Milkey59bc0722018-05-11 09:59:19 -07001894 if (mainEventExecutor == null) {
1895 return;
1896 }
Charles Chana8487b02018-04-18 18:41:05 -07001897 switch (event.type()) {
Saurav Dasc6dc1772018-04-21 17:19:48 -07001898 case MASTER_CHANGED:
1899 log.debug("Mastership event: {}/{}", event.subject(),
1900 event.roleInfo());
1901 mainEventExecutor.execute(new InternalEventHandler(event));
1902 break;
1903 case BACKUPS_CHANGED:
1904 case SUSPENDED:
1905 default:
1906 log.debug("Mastership event type {} not handled", event.type());
1907 break;
Charles Chana8487b02018-04-18 18:41:05 -07001908 }
1909 }
1910 }
1911
Saurav Dasc6dc1772018-04-21 17:19:48 -07001912 class InternalClusterListener implements ClusterEventListener {
1913 private Instant lastClusterEvent = Instant.EPOCH;
1914
1915 long timeSinceLastClusterEvent() {
1916 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1917 }
1918
1919 @Override
1920 public void event(ClusterEvent event) {
1921 switch (event.type()) {
1922 case INSTANCE_ACTIVATED:
1923 case INSTANCE_ADDED:
1924 case INSTANCE_READY:
1925 log.debug("Cluster event {} ignored", event.type());
1926 break;
1927 case INSTANCE_DEACTIVATED:
1928 case INSTANCE_REMOVED:
1929 log.info("** Cluster event {}", event.type());
1930 lastClusterEvent = Instant.now();
1931 break;
1932 default:
1933 break;
1934 }
1935
1936 }
1937
1938 }
1939
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001940 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1941 try {
1942 Set<Interface> intfs = conf.getInterfaces();
1943 Set<Interface> prevIntfs = prevConf.getInterfaces();
1944
1945 // Now we only handle one interface config at each port.
1946 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1947 log.warn("Interface update aborted - one at a time is allowed, " +
1948 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1949 return;
1950 }
1951
Andrea Campanellaab482f92018-04-17 12:09:34 +02001952 //The system is in an incoherent state, abort
1953 if (defaultRoutingHandler == null) {
1954 log.warn("Interface update aborted, defaultRoutingHandler is null");
1955 return;
1956 }
1957
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001958 Interface intf = intfs.stream().findFirst().get();
1959 Interface prevIntf = prevIntfs.stream().findFirst().get();
1960
1961 DeviceId deviceId = intf.connectPoint().deviceId();
1962 PortNumber portNum = intf.connectPoint().port();
1963
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001964 removeSubnetConfig(prevIntf.connectPoint(),
1965 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1966 new HashSet<>(intf.ipAddressesList())));
1967
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001968 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1969 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1970 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1971 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1972 // Update filtering objective and L2IG group bucket
1973 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1974 } else {
1975 // RemoveVlanNative
1976 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1977 }
1978 }
1979
1980 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1981 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1982 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1983 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1984 // Update filtering objective and L2IG group bucket
1985 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1986 } else {
1987 // RemoveVlanUntagged
1988 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1989 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001990 }
1991
1992 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1993 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001994 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1995 .filter(i -> !intf.vlanUntagged().equals(i))
1996 .filter(i -> !intf.vlanNative().equals(i))
1997 .forEach(vlanId -> updateVlanConfigInternal(
1998 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001999 }
2000
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002001 if (!intf.vlanNative().equals(VlanId.NONE)
2002 && !prevIntf.vlanNative().equals(intf.vlanNative())
2003 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2004 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2005 // Update filtering objective and L2IG group bucket
2006 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2007 } else {
2008 // AddVlanNative
2009 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2010 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002011 }
2012
2013 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2014 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002015 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2016 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2017 .filter(i -> !prevIntf.vlanNative().equals(i))
2018 .forEach(vlanId -> updateVlanConfigInternal(
2019 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002020 );
2021 }
2022
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002023 if (!intf.vlanUntagged().equals(VlanId.NONE)
2024 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2025 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2026 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2027 // Update filtering objective and L2IG group bucket
2028 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2029 } else {
2030 // AddVlanUntagged
2031 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2032 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002033 }
2034 addSubnetConfig(prevIntf.connectPoint(),
2035 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2036 new HashSet<>(prevIntf.ipAddressesList())));
2037 } catch (ConfigException e) {
2038 log.error("Error in configuration");
2039 }
2040 }
2041
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002042 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2043 VlanId vlanId, boolean pushVlan) {
2044 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2045 if (grpHandler == null) {
2046 log.warn("Failed to retrieve group handler for device {}", deviceId);
2047 return;
2048 }
2049
2050 // Update filtering objective for a single port
2051 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2052 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2053
2054 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2055 // Update L2IG bucket of the port
2056 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2057 } else {
2058 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2059 }
2060 }
2061
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002062 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2063 VlanId vlanId, boolean pushVlan, boolean install) {
2064 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2065 if (grpHandler == null) {
2066 log.warn("Failed to retrieve group handler for device {}", deviceId);
2067 return;
2068 }
2069
2070 // Update filtering objective for a single port
2071 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2072
2073 // Update filtering objective for multicast ingress port
2074 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2075
2076 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2077
2078 if (nextId != -1 && !install) {
2079 // Update next objective for a single port as an output port
2080 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002081 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002082 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chana03ab8b2018-04-29 18:11:37 -07002083 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2084 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002085 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2086 // only if there is no port configured on that VLAN ID
2087 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2088 // Remove broadcast forwarding rule for the VLAN
2089 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2090 // Remove L2FG for VLAN
2091 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2092 } else {
2093 // Remove L2IG of the port
2094 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2095 }
2096 } else if (install) {
2097 if (nextId != -1) {
2098 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09002099 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002100 } else {
2101 // Create L2FG for VLAN
2102 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2103 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2104 }
Charles Chana03ab8b2018-04-29 18:11:37 -07002105 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2106 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002107 } else {
2108 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2109 }
2110 }
2111
2112 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2113 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2114 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2115
2116 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2117 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2118 .filter(intf -> !intf.connectPoint().equals(cp))
2119 .flatMap(intf -> intf.ipAddressesList().stream())
2120 .collect(Collectors.toSet());
2121 // 1. Partial subnet population
2122 // Remove routing rules for removed subnet from previous configuration,
2123 // which does not also exist in other interfaces in the same device
2124 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2125 .map(InterfaceIpAddress::subnetAddress)
2126 .collect(Collectors.toSet());
2127
2128 defaultRoutingHandler.revokeSubnet(
2129 ipPrefixSet.stream()
2130 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2131 .collect(Collectors.toSet()));
2132
2133 // 2. Interface IP punts
2134 // Remove IP punts for old Intf address
2135 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2136 .map(InterfaceIpAddress::ipAddress)
2137 .collect(Collectors.toSet());
2138 ipAddressSet.stream()
2139 .map(InterfaceIpAddress::ipAddress)
2140 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2141 .forEach(interfaceIpAddress ->
2142 routingRulePopulator.revokeSingleIpPunts(
2143 cp.deviceId(), interfaceIpAddress));
2144
2145 // 3. Host unicast routing rule
2146 // Remove unicast routing rule
Charles Chana03ab8b2018-04-29 18:11:37 -07002147 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002148 }
2149
2150 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2151 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2152 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2153
2154 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2155 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2156 .filter(intf -> !intf.connectPoint().equals(cp))
2157 .flatMap(intf -> intf.ipAddressesList().stream())
2158 .collect(Collectors.toSet());
2159 // 1. Partial subnet population
2160 // Add routing rules for newly added subnet, which does not also exist in
2161 // other interfaces in the same device
2162 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2163 .map(InterfaceIpAddress::subnetAddress)
2164 .collect(Collectors.toSet());
2165
2166 defaultRoutingHandler.populateSubnet(
2167 Collections.singleton(cp),
2168 ipPrefixSet.stream()
2169 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2170 .collect(Collectors.toSet()));
2171
2172 // 2. Interface IP punts
2173 // Add IP punts for new Intf address
2174 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2175 .map(InterfaceIpAddress::ipAddress)
2176 .collect(Collectors.toSet());
2177 ipAddressSet.stream()
2178 .map(InterfaceIpAddress::ipAddress)
2179 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2180 .forEach(interfaceIpAddress ->
2181 routingRulePopulator.populateSingleIpPunts(
2182 cp.deviceId(), interfaceIpAddress));
2183
2184 // 3. Host unicast routing rule
2185 // Add unicast routing rule
Charles Chana03ab8b2018-04-29 18:11:37 -07002186 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002187 }
sanghob35a6192015-04-01 13:05:26 -07002188}