blob: 3c37d8057cfa24c08becbf55f1aa989bdf2de3b8 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-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 Hart61e24e12017-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 Chanf0ae41e2017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sangho80f11cb2015-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 Chan873661e2017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sangho80f11cb2015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070041import org.onosproject.cluster.ClusterEvent;
42import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010043import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070044import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020045import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.core.ApplicationId;
47import org.onosproject.core.CoreService;
48import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070049import org.onosproject.mastership.MastershipEvent;
50import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070051import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070052import org.onosproject.mcast.api.McastEvent;
53import org.onosproject.mcast.api.McastListener;
54import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080071import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070072import org.onosproject.net.device.DeviceEvent;
73import org.onosproject.net.device.DeviceListener;
74import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080075import org.onosproject.net.flow.TrafficSelector;
76import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070077import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070078import org.onosproject.net.flowobjective.NextObjective;
Charles Chanf4586112015-11-09 16:37:23 -080079import org.onosproject.net.host.HostEvent;
80import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070081import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080082import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070083import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020084import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070085import org.onosproject.net.intf.Interface;
86import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080087import org.onosproject.net.link.LinkEvent;
88import org.onosproject.net.link.LinkListener;
89import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070090import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-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 Luigid8a15162018-02-15 16:33:08 +010095import org.onosproject.net.topology.TopologyEvent;
96import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070097import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070098import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070099import org.onosproject.routeservice.RouteEvent;
100import org.onosproject.routeservice.RouteListener;
101import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -0700102import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
103import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -0800104import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700105import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -0700106import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -0700107import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700108import org.onosproject.segmentrouting.grouphandler.DestinationSet;
109import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi69f774d2018-02-28 12:10:50 +0100110import org.onosproject.segmentrouting.mcast.McastHandler;
111import org.onosproject.segmentrouting.mcast.McastRole;
Piere99511d2018-04-19 16:47:06 +0200112import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700116import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800117
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800118import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700119import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800121import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
122
Saurav Das261c3002017-06-13 15:35:54 -0700123import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700124import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Piere99511d2018-04-19 16:47:06 +0200125import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700126import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800127import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700128import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700129import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700130import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-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 Chan873661e2017-11-30 15:37:50 -0800135import org.osgi.service.component.ComponentContext;
sangho80f11cb2015-04-01 13:05:26 -0700136import org.slf4j.Logger;
137import org.slf4j.LoggerFactory;
138
Saurav Das00e553b2018-04-21 17:19:48 -0700139import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700140import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800141import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800142import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800143import java.util.HashSet;
144import java.util.List;
145import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800146import java.util.Optional;
147import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200148import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800149import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200150import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan77cdde42018-05-08 21:35:50 -0700151import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800152import java.util.concurrent.Executors;
153import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800154import java.util.concurrent.TimeUnit;
155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.stream.Collectors;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700157import java.util.stream.IntStream;
sangho80f11cb2015-04-01 13:05:26 -0700158
Charles Chand6d25332016-02-26 22:19:52 -0800159import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800160import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700161import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-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 Chand6d25332016-02-26 22:19:52 -0800164
Charles Chanb7f75ac2016-01-11 18:28:54 -0800165/**
166 * Segment routing manager.
167 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700168@Service
169@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700170public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700171
Charles Chan46fdfaf2016-11-09 20:51:44 -0800172 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700173 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700176 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800179 private NeighbourResolutionService neighbourResolutionService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100182 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700185 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700188 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700191 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100194 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800197 DeviceAdminService deviceAdminService;
198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800200 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100203 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700204
Charles Chan82ab1932016-01-30 23:22:37 -0800205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800206 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700207
208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800209 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700210
211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100212 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700213
214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan83163812018-01-09 13:45:07 -0800215 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700216
217 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700218 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800219
220 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800221 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800222
Saurav Dasc3604f12016-03-23 11:22:49 -0700223 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800224 public InterfaceService interfaceService;
225
Pier Luigi580fd8a2018-01-16 10:47:50 +0100226 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
227 public ClusterService clusterService;
228
229 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pierdb27b8d2018-04-17 16:29:56 +0200230 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100231
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700232 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
233 public LeadershipService leadershipService;
234
Charles Chan8d316332018-06-19 20:31:57 -0700235 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
236 public XconnectService xconnectService;
237
Charles Chan873661e2017-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
Mayank Tiwarif7942402018-10-29 18:27:35 -0400242 @Property(name = "symmetricProbing", boolValue = false,
243 label = "Enable only send probe on the same port number of the pair device")
244 boolean symmetricProbing = false;
245
Saurav Dasec683dc2018-04-27 18:42:30 -0700246 @Property(name = "singleHomedDown", boolValue = false,
247 label = "Enable administratively taking down single-homed hosts "
248 + "when all uplinks are gone")
249 boolean singleHomedDown = false;
250
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700251 @Property(name = "respondToUnknownHosts", boolValue = true,
252 label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
253 boolean respondToUnknownHosts = true;
254
Charles Chanfbca55e2018-07-24 16:40:35 -0700255 @Property(name = "routeDoubleTaggedHosts", boolValue = false,
256 label = "Program flows and groups to pop and route double tagged hosts")
257 boolean routeDoubleTaggedHosts = false;
Charles Chan4eb73bb2018-07-19 14:55:31 -0700258
Saurav Das9bf49582018-08-13 15:34:26 -0700259 private static final int DEFAULT_INTERNAL_VLAN = 4094;
260 @Property(name = "defaultInternalVlan", intValue = DEFAULT_INTERNAL_VLAN,
261 label = "internal vlan assigned by default to unconfigured ports")
262 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN;
263
264 private static final int PW_TRANSPORT_VLAN = 4090;
265 @Property(name = "pwTransportVlan", intValue = PW_TRANSPORT_VLAN,
266 label = "vlan used for transport of pseudowires between switches")
267 private int pwTransportVlan = PW_TRANSPORT_VLAN;
268
Charles Chandebfea32016-10-24 14:52:01 -0700269 ArpHandler arpHandler = null;
270 IcmpHandler icmpHandler = null;
271 IpHandler ipHandler = null;
272 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700273 ApplicationId appId;
274 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700275
Charles Chandebfea32016-10-24 14:52:01 -0700276 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700277 private TunnelHandler tunnelHandler = null;
278 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700279 private InternalPacketProcessor processor = null;
280 private InternalLinkListener linkListener = null;
281 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700282 private AppConfigHandler appCfgHandler = null;
Pier Luigi69f774d2018-02-28 12:10:50 +0100283 public XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800284 McastHandler mcastHandler = null;
285 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800286 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800287 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800288 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800289 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100290 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800291 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700292 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
293 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700294 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100295 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700296 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700297 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200298 //Completable future for network configuration process to buffer config events handling during activation
299 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan39b75522018-04-21 00:44:29 -0700300 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700301
Charles Chan52003922018-04-05 16:31:15 -0700302 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700303 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700304
Charles Chanfbcb8812018-04-18 18:41:05 -0700305 // Handles host, route and mcast events respectively
306 private ScheduledExecutorService hostEventExecutor;
307 private ScheduledExecutorService routeEventExecutor;
308 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700309 private ExecutorService packetExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700310
311 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800312 /**
Saurav Das261c3002017-06-13 15:35:54 -0700313 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700314 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800315 */
Charles Chan873661e2017-11-30 15:37:50 -0800316 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700317 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800318 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700319 * Per device next objective ID store with (device id + vlanid) as key.
320 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800321 */
Charles Chan873661e2017-11-30 15:37:50 -0800322 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800323 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800324 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700325 * Per device next objective ID store with (device id + port + treatment + meta) as key.
326 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800327 */
Charles Chan873661e2017-11-30 15:37:50 -0800328 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800329 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800330
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700331 /**
332 * Per port dummy VLAN ID store with (connect point + ip address) as key.
333 * Used to keep track on dummy VLAN ID allocation.
334 */
335 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
336 dummyVlanIdStore = null;
337
Saurav Das2d94d312015-11-24 23:21:05 -0800338 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
339 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700340
Saurav Das261c3002017-06-13 15:35:54 -0700341 private AtomicBoolean programmingScheduled = new AtomicBoolean();
342
Charles Chanc91c8782016-03-30 17:54:24 -0700343 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700344 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
345 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700346 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700347 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800348 public SegmentRoutingDeviceConfig createConfig() {
349 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700350 }
351 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800352
Charles Chanc91c8782016-03-30 17:54:24 -0700353 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700354 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
355 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700356 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800357 @Override
358 public SegmentRoutingAppConfig createConfig() {
359 return new SegmentRoutingAppConfig();
360 }
361 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800362
Charles Chan82f19972016-05-17 13:13:55 -0700363 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
364 new ConfigFactory<ApplicationId, XConnectConfig>(
365 SubjectFactories.APP_SUBJECT_FACTORY,
366 XConnectConfig.class, "xconnect") {
367 @Override
368 public XConnectConfig createConfig() {
369 return new XConnectConfig();
370 }
371 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800372
Charles Chanc91c8782016-03-30 17:54:24 -0700373 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700374 new ConfigFactory<ApplicationId, McastConfig>(
375 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700376 McastConfig.class, "multicast") {
377 @Override
378 public McastConfig createConfig() {
379 return new McastConfig();
380 }
381 };
382
Charles Chan1963f4f2016-02-18 14:22:42 -0800383 /**
384 * Segment Routing App ID.
385 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800386 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das7c305372015-10-28 12:39:42 -0700387
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700388 /**
389 * Minumum and maximum value of dummy VLAN ID to be allocated.
390 */
391 public static final int MIN_DUMMY_VLAN_ID = 2;
392 public static final int MAX_DUMMY_VLAN_ID = 4093;
393
Saurav Dasec683dc2018-04-27 18:42:30 -0700394 Instant lastEdgePortEvent = Instant.EPOCH;
395
sangho80f11cb2015-04-01 13:05:26 -0700396 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800397 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800398 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700399
Charles Chanfbcb8812018-04-18 18:41:05 -0700400 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
401 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
402 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
403 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan77cdde42018-05-08 21:35:50 -0700404 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700405
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700406 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700407 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700408 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700409 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700410 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700411 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700412 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700413 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700414 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700415
Charles Chan10b0fb72017-02-02 16:20:42 -0800416 log.debug("Creating EC map vlannextobjectivestore");
417 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
418 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
419 vlanNextObjStore = vlanNextObjMapBuilder
420 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700421 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700422 .withTimestampProvider((k, v) -> new WallClockTimestamp())
423 .build();
424
Saurav Das2d94d312015-11-24 23:21:05 -0800425 log.debug("Creating EC map subnetnextobjectivestore");
426 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
427 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
428 portNextObjStore = portNextObjMapBuilder
429 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700430 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800431 .withTimestampProvider((k, v) -> new WallClockTimestamp())
432 .build();
433
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700434 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
435 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
436 dummyVlanIdStore = dummyVlanIdMapBuilder
437 .withName("dummyvlanidstore")
438 .withSerializer(createSerializer())
439 .withTimestampProvider((k, v) -> new WallClockTimestamp())
440 .build();
441
sangho4a5c42a2015-05-20 22:16:38 -0700442 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
443 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700444 tunnelStore = tunnelMapBuilder
445 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700446 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700447 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700448 .build();
449
450 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
451 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700452 policyStore = policyMapBuilder
453 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700454 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700455 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700456 .build();
457
Saurav Dasc3604f12016-03-23 11:22:49 -0700458 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800459 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700460 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800461 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800462 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
463 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700464 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800465 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700466 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800467 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800468 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
469 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800470 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
471 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700472 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700473 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700474 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
475 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800476 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
477 "staleLinkAge", "15000");
478 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
479 "allowDuplicateIps", "false");
Yi Tsenga7da8d82018-08-19 03:09:54 +0800480 // For P4 switches
481 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan02298512018-08-30 17:30:45 -0700482 "fallbackFlowPollFrequency", "4");
Yi Tsenga7da8d82018-08-19 03:09:54 +0800483 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan02298512018-08-30 17:30:45 -0700484 "fallbackGroupPollFrequency", "3");
Charles Chan873661e2017-11-30 15:37:50 -0800485 compCfgService.registerProperties(getClass());
486 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700487
Charles Chan2b078ae2015-10-14 11:24:40 -0700488 processor = new InternalPacketProcessor();
489 linkListener = new InternalLinkListener();
490 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700491 appCfgHandler = new AppConfigHandler(this);
492 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700493 mcastHandler = new McastHandler(this);
494 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800495 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700496 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800497 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800498 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigid8a15162018-02-15 16:33:08 +0100499 topologyHandler = new TopologyHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700500
Charles Chand6d25332016-02-26 22:19:52 -0800501 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700502 cfgService.registerConfigFactory(deviceConfigFactory);
503 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700504 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700505 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800506 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200507
Charles Chan6961f222018-01-04 14:26:07 -0800508 cfgListener.configureNetwork();
509
Charles Chan82ab1932016-01-30 23:22:37 -0800510 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700511 packetService.addProcessor(processor, PacketProcessor.director(2));
512 linkService.addListener(linkListener);
513 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700514 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700515 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100516 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700517 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700518 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700519
Charles Chanc12c3d02018-03-09 15:53:44 -0800520 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800521 l2TunnelHandler.init();
522
Andrea Campanella060cad82018-04-17 12:09:34 +0200523 networkConfigCompletion.whenComplete((value, ex) -> {
524 //setting to null for easier fall through
525 networkConfigCompletion = null;
526 //process all queued events
Charles Chan39b75522018-04-21 00:44:29 -0700527 queuedEvents.forEach(event -> {
Andrea Campanella060cad82018-04-17 12:09:34 +0200528 mainEventExecutor.execute(new InternalEventHandler(event));
529 });
530 });
531
sangho80f11cb2015-04-01 13:05:26 -0700532 log.info("Started");
533 }
534
Saurav Dase6c448a2018-01-18 12:07:33 -0800535 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700536 return new KryoNamespace.Builder()
537 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700538 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800539 VlanNextObjectiveStoreKey.class,
540 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700541 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800542 NextNeighbors.class,
543 Tunnel.class,
544 DefaultTunnel.class,
545 Policy.class,
546 TunnelPolicy.class,
547 Policy.Type.class,
548 PortNextObjectiveStoreKey.class,
549 XConnectStoreKey.class,
550 L2Tunnel.class,
551 L2TunnelPolicy.class,
552 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700553 DefaultL2TunnelPolicy.class,
554 DummyVlanIdStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700555 );
556 }
557
sangho80f11cb2015-04-01 13:05:26 -0700558 @Deactivate
559 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700560 mainEventExecutor.shutdown();
561 hostEventExecutor.shutdown();
562 routeEventExecutor.shutdown();
563 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700564 packetExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700565
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700566 mainEventExecutor = null;
567 hostEventExecutor = null;
568 routeEventExecutor = null;
569 mcastEventExecutor = null;
570 packetExecutor = null;
571
Charles Chan72f556a2015-10-05 17:50:33 -0700572 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700573 cfgService.unregisterConfigFactory(deviceConfigFactory);
574 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700575 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700576 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800577 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700578
Charles Chanfd48c222017-06-19 00:43:31 -0700579 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700580 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700581 linkService.removeListener(linkListener);
582 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700583 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700584 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100585 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700586 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700587 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700588
Charles Chan2e71ef32017-02-23 15:44:08 -0800589 neighbourResolutionService.unregisterNeighbourHandlers(appId);
590
sangho80f11cb2015-04-01 13:05:26 -0700591 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700592 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700593 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700594 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700595 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700596 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700597
Saurav Das261c3002017-06-13 15:35:54 -0700598 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800599 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700600 portNextObjStore.destroy();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700601 dummyVlanIdStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700602 tunnelStore.destroy();
603 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100604
605 mcastHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700606 log.info("Stopped");
607 }
608
Charles Chan873661e2017-11-30 15:37:50 -0800609 @Modified
610 private void modified(ComponentContext context) {
611 Dictionary<?, ?> properties = context.getProperties();
612 if (properties == null) {
613 return;
614 }
615
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700616 String strActiveProbing = Tools.get(properties, "activeProbing");
617 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800618 if (expectActiveProbing != activeProbing) {
619 activeProbing = expectActiveProbing;
620 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
621 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700622
Mayank Tiwarif7942402018-10-29 18:27:35 -0400623 String strSymmetricProving = Tools.get(properties, "symmetricProbing");
624 boolean expectSymmetricProbing = Boolean.parseBoolean(strSymmetricProving);
625 if (expectSymmetricProbing != symmetricProbing) {
626 symmetricProbing = expectSymmetricProbing;
627 log.info("{} symmetric probing", symmetricProbing ? "Enabling" : "Disabling");
628 }
629
Saurav Dasec683dc2018-04-27 18:42:30 -0700630 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
631 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
632 if (expectSingleHomedDown != singleHomedDown) {
633 singleHomedDown = expectSingleHomedDown;
634 log.info("{} downing of single homed hosts for lost uplinks",
635 singleHomedDown ? "Enabling" : "Disabling");
636 if (singleHomedDown && linkHandler != null) {
637 hostService.getHosts().forEach(host -> host.locations()
638 .forEach(loc -> {
639 if (interfaceService.isConfigured(loc)) {
640 linkHandler.checkUplinksForHost(loc);
641 }
642 }));
643 } else {
644 log.warn("Disabling singleHomedDown does not re-enable already "
645 + "downed ports for single-homed hosts");
646 }
647 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700648
649 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
650 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
651 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
652 respondToUnknownHosts = expectRespondToUnknownHosts;
653 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
654 }
Charles Chan4eb73bb2018-07-19 14:55:31 -0700655
Charles Chanfbca55e2018-07-24 16:40:35 -0700656 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
657 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
658 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
659 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
660 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan4eb73bb2018-07-19 14:55:31 -0700661
Charles Chanfbca55e2018-07-24 16:40:35 -0700662 if (routeDoubleTaggedHosts) {
Charles Chan4eb73bb2018-07-19 14:55:31 -0700663 hostHandler.populateAllDoubleTaggedHost();
664 } else {
665 hostHandler.revokeAllDoubleTaggedHost();
666 }
667 }
Saurav Das9bf49582018-08-13 15:34:26 -0700668
669 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
670 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
671 if (defIntVlan != defaultInternalVlan) {
672 if (canUseVlanId(defIntVlan)) {
673 log.warn("Default internal vlan value changed from {} to {}.. "
674 + "re-programming filtering rules, but NOT any groups already "
675 + "created with the former value", defaultInternalVlan, defIntVlan);
676 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
677 defaultInternalVlan = defIntVlan;
678 routingRulePopulator
679 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
680 VlanId.vlanId((short) defIntVlan));
681 } else {
682 log.warn("Cannot change default internal vlan to unusable "
683 + "value {}", defIntVlan);
684 }
685 }
686
687 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
688 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
689 if (pwTxpVlan != pwTransportVlan) {
690 if (canUseVlanId(pwTxpVlan)) {
691 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
692 + "re-programming filtering rules, but NOT any groups already "
693 + "created with the former value", pwTransportVlan,
694 pwTxpVlan);
695 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
696 pwTransportVlan = pwTxpVlan;
697 routingRulePopulator
698 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
699 VlanId.vlanId((short) pwTxpVlan));
700 } else {
701 log.warn("Cannot change pseudowire transport vlan to unusable "
702 + "value {}", pwTxpVlan);
703 }
704 }
705
706 }
707
708 /**
709 * Returns true if given vlan id is not being used in the system currently,
710 * either as one of the default system wide vlans or as one of the
711 * configured interface vlans.
712 *
713 * @param vlanId given vlan id
714 * @return true if vlan is not currently in use
715 */
716 public boolean canUseVlanId(int vlanId) {
717 if (vlanId >= 4095 || vlanId <= 1) {
718 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
719 vlanId);
720 return false;
721 }
722
723 VlanId vid = VlanId.vlanId((short) vlanId);
724 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
725 log.warn("Vlan id {} value is already in use system-wide. "
726 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
727 getDefaultInternalVlan(), getPwTransportVlan());
728 return false;
729 }
730
731 if (interfaceService.inUse(vid)) {
732 log.warn("Vlan id {} value is already in use on a configured "
733 + "interface in the system", vlanId);
734 return false;
735 }
736 return true;
737 }
738
739 /**
740 * Returns the VlanId assigned internally by default to unconfigured ports.
741 *
742 * @return the default internal vlan id
743 */
744 public VlanId getDefaultInternalVlan() {
745 return VlanId.vlanId((short) defaultInternalVlan);
746 }
747
748 /**
749 * Returns the Vlan id used to transport pseudowire traffic across the
750 * network.
751 *
752 * @return the pseudowire transport vlan id
753 */
754 public VlanId getPwTransportVlan() {
755 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan873661e2017-11-30 15:37:50 -0800756 }
757
sangho27462c62015-05-14 00:39:53 -0700758 @Override
759 public List<Tunnel> getTunnels() {
760 return tunnelHandler.getTunnels();
761 }
762
763 @Override
sanghobd812f82015-06-29 14:58:47 -0700764 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
765 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700766 }
767
768 @Override
sanghobd812f82015-06-29 14:58:47 -0700769 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700770 for (Policy policy: policyHandler.getPolicies()) {
771 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
772 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
773 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
774 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700775 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700776 }
777 }
778 }
sanghobd812f82015-06-29 14:58:47 -0700779 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700780 }
781
782 @Override
sanghobd812f82015-06-29 14:58:47 -0700783 public PolicyHandler.Result removePolicy(Policy policy) {
784 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700785 }
786
787 @Override
sanghobd812f82015-06-29 14:58:47 -0700788 public PolicyHandler.Result createPolicy(Policy policy) {
789 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700790 }
791
792 @Override
793 public List<Policy> getPolicies() {
794 return policyHandler.getPolicies();
795 }
796
Saurav Das07c74602016-04-27 18:35:50 -0700797 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700798 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
799 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700800 }
801
802 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800803 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700804 return l2TunnelHandler.getL2Tunnels();
805 }
806
807 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800808 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700809 return l2TunnelHandler.getL2Policies();
810 }
811
Saurav Dasdebcf882018-04-06 20:16:01 -0700812 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700813 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700814 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
815
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700816 // get both added and pending pseudowires
817 List<L2TunnelDescription> pseudowires = new ArrayList<>();
818 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
819 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700820 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700821
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700822 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
823
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700824 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
825 L2TunnelHandler.Result res;
826 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
827 res = addPseudowire(pw);
828 if (res != L2TunnelHandler.Result.SUCCESS) {
829 log.error("Pseudowire with id {} can not be instantiated !", res);
830 retRes = res;
831 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700832 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700833
834 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700835 }
836
837 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800838 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700839 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700840 }
841
842 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800843 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700844 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700845 }
846
847 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700848 public void rerouteNetwork() {
849 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700850 }
851
Charles Chand7844e52016-10-20 17:02:44 -0700852 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800853 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
854 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800855 deviceConfiguration.getRouters().forEach(device ->
856 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700857 return deviceSubnetMap;
858 }
859
Saurav Das62ae6792017-05-15 15:34:25 -0700860
861 @Override
862 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
863 if (defaultRoutingHandler != null) {
864 return defaultRoutingHandler.getCurrentEmcpSpgMap();
865 } else {
866 return null;
867 }
868 }
869
870 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700871 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das261c3002017-06-13 15:35:54 -0700872 if (dsNextObjStore != null) {
873 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700874 } else {
875 return ImmutableMap.of();
876 }
877 }
878
Saurav Dasfbe74572017-08-03 18:30:35 -0700879 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700880 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
881 if (vlanNextObjStore != null) {
882 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
883 } else {
884 return ImmutableMap.of();
885 }
886 }
887
888 @Override
889 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
890 if (portNextObjStore != null) {
891 return ImmutableMap.copyOf(portNextObjStore.entrySet());
892 } else {
893 return ImmutableMap.of();
894 }
895 }
896
897 @Override
898 public ImmutableMap<String, NextObjective> getPwInitNext() {
899 if (l2TunnelHandler != null) {
900 return l2TunnelHandler.getInitNext();
901 } else {
902 return ImmutableMap.of();
903 }
904 }
905
906 @Override
907 public ImmutableMap<String, NextObjective> getPwTermNext() {
908 if (l2TunnelHandler != null) {
909 return l2TunnelHandler.getTermNext();
910 } else {
911 return ImmutableMap.of();
912 }
913 }
914
915 @Override
916 public void invalidateNextObj(int nextId) {
917 if (dsNextObjStore != null) {
918 dsNextObjStore.entrySet().forEach(e -> {
919 if (e.getValue().nextId() == nextId) {
920 dsNextObjStore.remove(e.getKey());
921 }
922 });
923 }
924 if (vlanNextObjStore != null) {
925 vlanNextObjStore.entrySet().forEach(e -> {
926 if (e.getValue() == nextId) {
927 vlanNextObjStore.remove(e.getKey());
928 }
929 });
930 }
931 if (portNextObjStore != null) {
932 portNextObjStore.entrySet().forEach(e -> {
933 if (e.getValue() == nextId) {
934 portNextObjStore.remove(e.getKey());
935 }
936 });
937 }
938 if (mcastHandler != null) {
939 mcastHandler.removeNextId(nextId);
940 }
941 if (l2TunnelHandler != null) {
942 l2TunnelHandler.removeNextId(nextId);
943 }
944 if (xconnectService != null) {
945 xconnectService.removeNextId(nextId);
946 }
947 }
948
949 @Override
Saurav Dasfbe74572017-08-03 18:30:35 -0700950 public void verifyGroups(DeviceId id) {
951 DefaultGroupHandler gh = groupHandlerMap.get(id);
952 if (gh != null) {
953 gh.triggerBucketCorrector();
954 }
955 }
956
Saurav Das6430f412018-01-25 09:49:01 -0800957 @Override
958 public ImmutableMap<Link, Boolean> getSeenLinks() {
959 return linkHandler.getSeenLinks();
960 }
961
962 @Override
963 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
964 return linkHandler.getDownedPorts();
965 }
966
Pier Luigi0f9635b2018-01-15 18:06:43 +0100967 @Override
968 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700969 return mcastHandler.getNextIds(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +0100970 }
971
972 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +0100973 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +0100974 return mcastHandler.getMcastRoles(mcastIp);
975 }
976
977 @Override
Piere99511d2018-04-19 16:47:06 +0200978 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
979 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
980 }
981
982 @Override
Pier Luigi0f9635b2018-01-15 18:06:43 +0100983 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
984 return mcastHandler.getMcastPaths(mcastIp);
985 }
986
Pierdb27b8d2018-04-17 16:29:56 +0200987 @Override
Pier71c55772018-04-17 17:25:22 +0200988 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
989 ConnectPoint sourcecp) {
990 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
991 }
992
993 @Override
Pierdb27b8d2018-04-17 16:29:56 +0200994 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
995 return mcastHandler.getMcastLeaders(mcastIp);
996 }
997
Charles Chanb13e0702018-04-17 18:56:53 -0700998 @Override
999 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
1000 return defaultRoutingHandler == null ? ImmutableMap.of() :
1001 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
1002 }
1003
1004 @Override
1005 public Map<DeviceId, Boolean> getShouldProgramCache() {
1006 return defaultRoutingHandler == null ? ImmutableMap.of() :
1007 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
1008 }
1009
Charles Chan8d316332018-06-19 20:31:57 -07001010 @Override
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301011 public boolean shouldProgram(DeviceId deviceId) {
1012 return defaultRoutingHandler.shouldProgram(deviceId);
1013 }
1014
1015 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -07001016 public ApplicationId appId() {
1017 return appId;
1018 }
1019
1020 /**
1021 * Returns the device configuration.
1022 *
1023 * @return device configuration
1024 */
1025 public DeviceConfiguration deviceConfiguration() {
1026 return deviceConfiguration;
1027 }
1028
1029 /**
Saurav Das261c3002017-06-13 15:35:54 -07001030 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -07001031 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001032 *
1033 * @return next objective ID store
1034 */
Saurav Das261c3002017-06-13 15:35:54 -07001035 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1036 dsNextObjStore() {
1037 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -07001038 }
1039
1040 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001041 * Per device next objective ID store with (device id + vlanid) as key.
1042 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001043 *
1044 * @return vlan next object store
1045 */
1046 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1047 return vlanNextObjStore;
1048 }
1049
1050 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001051 * Per device next objective ID store with (device id + port + treatment + meta) as key.
1052 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001053 *
1054 * @return port next object store.
1055 */
1056 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1057 return portNextObjStore;
1058 }
1059
1060 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001061 * Per port dummy VLAN ID store with (connect point + ip address) as key.
1062 * Used to keep track on dummy VLAN ID allocation.
1063 *
1064 * @return dummy vlan id store.
1065 */
1066 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
1067 return dummyVlanIdStore;
1068 }
1069
1070 /**
Saurav Das261c3002017-06-13 15:35:54 -07001071 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1072 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -07001073 *
1074 * @return MPLS-ECMP value
1075 */
1076 public boolean getMplsEcmp() {
1077 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1078 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1079 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1080 }
1081
1082 /**
sangho80f1f892015-05-19 11:57:42 -07001083 * Returns the tunnel object with the tunnel ID.
1084 *
1085 * @param tunnelId Tunnel ID
1086 * @return Tunnel reference
1087 */
sangho27462c62015-05-14 00:39:53 -07001088 public Tunnel getTunnel(String tunnelId) {
1089 return tunnelHandler.getTunnel(tunnelId);
1090 }
1091
Charles Chan8d316332018-06-19 20:31:57 -07001092 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +01001093 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -07001094 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1095 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -07001096 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1097 }
1098
Charles Chan8d316332018-06-19 20:31:57 -07001099 @Override
1100 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001101 SegmentRoutingDeviceConfig deviceConfig =
1102 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1103 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1104 }
Charles Chan8d316332018-06-19 20:31:57 -07001105
1106 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -07001107 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001108 SegmentRoutingDeviceConfig deviceConfig =
1109 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1110 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1111 }
1112
1113 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -07001114 * Returns locations of given resolved route.
1115 *
1116 * @param resolvedRoute resolved route
1117 * @return locations of nexthop. Might be empty if next hop is not found
1118 */
1119 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1120 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1121 return Optional.ofNullable(hostService.getHost(hostId))
1122 .map(Host::locations).orElse(Sets.newHashSet())
1123 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1124 }
1125
1126 /**
Charles Chan90772a72017-02-08 15:52:08 -08001127 * Returns vlan port map of given device.
1128 *
1129 * @param deviceId device id
1130 * @return vlan-port multimap
1131 */
1132 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1133 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1134
1135 interfaceService.getInterfaces().stream()
1136 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1137 .forEach(intf -> {
1138 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -07001139 intf.vlanTagged().forEach(vlanTagged ->
1140 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1141 );
Charles Chan90772a72017-02-08 15:52:08 -08001142 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1143 });
1144 vlanPortMap.removeAll(VlanId.NONE);
1145
1146 return vlanPortMap;
1147 }
1148
1149 /**
Charles Chan10b0fb72017-02-02 16:20:42 -08001150 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -08001151 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -07001152 *
1153 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -08001154 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -08001155 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -07001156 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001157 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -07001158 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -08001159 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1160 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -07001161 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -08001162 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -08001163 + "device {} not found", deviceId);
1164 return -1;
1165 }
1166 }
1167
1168 /**
1169 * Returns the next objective ID for the given portNumber, given the treatment.
1170 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -07001171 * would result in different objectives. If the next object does not exist,
1172 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -08001173 *
1174 * @param deviceId Device ID
1175 * @param portNum port number on device for which NextObjective is queried
1176 * @param treatment the actions to apply on the packets (should include outport)
1177 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -07001178 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -07001179 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -08001180 */
1181 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1182 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -07001183 TrafficSelector meta,
1184 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -08001185 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1186 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -07001187 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -08001188 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -08001189 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1190 + " not found", deviceId);
1191 return -1;
1192 }
1193 }
1194
Saurav Das62ae6792017-05-15 15:34:25 -07001195 /**
1196 * Returns the group handler object for the specified device id.
1197 *
1198 * @param devId the device identifier
1199 * @return the groupHandler object for the device id, or null if not found
1200 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001201 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001202 return groupHandlerMap.get(devId);
1203 }
1204
1205 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001206 * Returns the default routing handler object.
1207 *
1208 * @return the default routing handler object
1209 */
1210 public DefaultRoutingHandler getRoutingHandler() {
1211 return defaultRoutingHandler;
1212 }
1213
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001214 /**
1215 * Returns new dummy VLAN ID.
1216 * Dummy VLAN ID should be unique in each connect point.
1217 *
1218 * @param cp connect point
1219 * @param ipAddress IP address
1220 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1221 */
1222 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1223 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1224 dummyVlanIdStore.entrySet().stream().filter(entry ->
1225 (entry.getKey()).connectPoint().equals(cp))
1226 .map(Map.Entry::getValue)
1227 .collect(Collectors.toSet()));
1228
1229 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1230 i -> VlanId.vlanId((short) (i & 0xFFFF))
1231 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1232
1233 if (!dummyVlanId.equals(VlanId.NONE)) {
1234 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1235 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1236 } else {
1237 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1238 }
1239 return dummyVlanId;
1240 }
1241
1242
sangho80f11cb2015-04-01 13:05:26 -07001243 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001244 @Override
1245 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001246 packetExecutor.execute(() -> processPacketInternal(context));
1247 }
sangho80f11cb2015-04-01 13:05:26 -07001248
Charles Chan77cdde42018-05-08 21:35:50 -07001249 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001250 if (context.isHandled()) {
1251 return;
1252 }
1253
1254 InboundPacket pkt = context.inPacket();
1255 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001256
1257 if (ethernet == null) {
1258 return;
1259 }
1260
Saurav Das261c3002017-06-13 15:35:54 -07001261 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1262 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001263 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001264 log.warn("Received unexpected ARP packet on {}",
1265 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001266 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001267 return;
sangho80f11cb2015-04-01 13:05:26 -07001268 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001269 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1270 //ipHandler.addToPacketBuffer(ipv4Packet);
1271 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1272 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001273 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001274 // NOTE: We don't support IP learning at this moment so this
1275 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001276 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001277 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001278 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1279 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001280 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001281 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001282 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1283 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1284 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1285 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1286 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1287 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001288 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001289 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001290 }
1291 } else {
1292 // NOTE: We don't support IP learning at this moment so this
1293 // is not necessary. Also it causes duplication of DHCPv6 packets.
1294 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1295 }
sangho80f11cb2015-04-01 13:05:26 -07001296 }
1297 }
1298 }
1299
sangho80f11cb2015-04-01 13:05:26 -07001300 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001301 private Event event;
1302
1303 InternalEventHandler(Event event) {
1304 this.event = event;
1305 }
1306
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001307 @Override
sangho80f11cb2015-04-01 13:05:26 -07001308 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001309 try {
1310 // TODO We should also change SR routing and PW to listen to TopologyEvents
1311 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1312 event.type() == LinkEvent.Type.LINK_UPDATED) {
1313 linkHandler.processLinkAdded((Link) event.subject());
1314 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1315 linkHandler.processLinkRemoved((Link) event.subject());
1316 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1317 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1318 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1319 DeviceId deviceId = ((Device) event.subject()).id();
1320 if (deviceService.isAvailable(deviceId)) {
1321 log.info("** DEVICE UP Processing device event {} "
1322 + "for available device {}",
1323 event.type(), ((Device) event.subject()).id());
1324 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001325 } else {
Charles Chanb8f3af52018-08-29 21:21:51 -07001326 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1327 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1328 // The device will later on being marked as available once the pipeline is pushed
1329 // to the device.
1330 log.info("** DEVICE ADDED but unavailable. Ignore");
1331 return;
1332 }
Charles Chan52003922018-04-05 16:31:15 -07001333 log.info(" ** DEVICE DOWN Processing device event {}"
1334 + " for unavailable device {}",
1335 event.type(), ((Device) event.subject()).id());
1336 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001337 }
Charles Chan52003922018-04-05 16:31:15 -07001338 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1339 // typically these calls come when device is added first time
1340 // so port filtering rules are handled at the device_added event.
1341 // port added calls represent all ports on the device,
1342 // enabled or not.
1343 log.trace("** PORT ADDED {}/{} -> {}",
1344 ((DeviceEvent) event).subject().id(),
1345 ((DeviceEvent) event).port().number(),
1346 event.type());
1347 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1348 // these calls happen for every subsequent event
1349 // ports enabled, disabled, switch goes away, comes back
1350 log.info("** PORT UPDATED {}/{} -> {}",
1351 event.subject(),
1352 ((DeviceEvent) event).port(),
1353 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001354 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001355 ((DeviceEvent) event).port());
1356 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1357 // Process topology event, needed for all modules relying on
1358 // topology service for path computation
1359 TopologyEvent topologyEvent = (TopologyEvent) event;
1360 log.info("Processing topology event {}, topology age {}, reasons {}",
1361 event.type(), topologyEvent.subject().time(),
1362 topologyEvent.reasons().size());
1363 topologyHandler.processTopologyChange(topologyEvent.reasons());
1364 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1365 hostHandler.processHostAddedEvent((HostEvent) event);
1366 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1367 hostHandler.processHostMovedEvent((HostEvent) event);
1368 routeHandler.processHostMovedEvent((HostEvent) event);
1369 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1370 hostHandler.processHostRemovedEvent((HostEvent) event);
1371 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1372 hostHandler.processHostUpdatedEvent((HostEvent) event);
1373 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1374 routeHandler.processRouteAdded((RouteEvent) event);
1375 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1376 routeHandler.processRouteUpdated((RouteEvent) event);
1377 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1378 routeHandler.processRouteRemoved((RouteEvent) event);
1379 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1380 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1381 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1382 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1383 event.type() == McastEvent.Type.SINKS_ADDED ||
1384 event.type() == McastEvent.Type.SINKS_REMOVED ||
1385 event.type() == McastEvent.Type.ROUTE_ADDED ||
1386 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1387 mcastHandler.processMcastEvent((McastEvent) event);
1388 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1389 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1390 Class configClass = netcfgEvent.configClass();
1391 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1392 appCfgHandler.processAppConfigAdded(netcfgEvent);
1393 log.info("App config event .. configuring network");
1394 cfgListener.configureNetwork();
1395 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1396 log.info("Segment Routing Device Config added for {}", event.subject());
1397 cfgListener.configureNetwork();
1398 } else if (configClass.equals(XConnectConfig.class)) {
1399 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1400 } else if (configClass.equals(InterfaceConfig.class)) {
1401 log.info("Interface Config added for {}", event.subject());
1402 cfgListener.configureNetwork();
1403 } else {
1404 log.error("Unhandled config class: {}", configClass);
1405 }
1406 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1407 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1408 Class configClass = netcfgEvent.configClass();
1409 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1410 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1411 log.info("App config event .. configuring network");
1412 cfgListener.configureNetwork();
1413 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1414 log.info("Segment Routing Device Config updated for {}", event.subject());
1415 createOrUpdateDeviceConfiguration();
1416 } else if (configClass.equals(XConnectConfig.class)) {
1417 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1418 } else if (configClass.equals(InterfaceConfig.class)) {
1419 log.info("Interface Config updated for {}", event.subject());
1420 createOrUpdateDeviceConfiguration();
1421 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1422 (InterfaceConfig) netcfgEvent.prevConfig().get());
1423 } else {
1424 log.error("Unhandled config class: {}", configClass);
1425 }
1426 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1427 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1428 Class configClass = netcfgEvent.configClass();
1429 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1430 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1431 log.info("App config event .. configuring network");
1432 cfgListener.configureNetwork();
1433 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1434 // TODO Handle sr device config removal
1435 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1436 } else if (configClass.equals(XConnectConfig.class)) {
1437 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1438 } else if (configClass.equals(InterfaceConfig.class)) {
1439 // TODO Handle interface removal
1440 log.info("InterfaceConfig removal is not handled in current implementation");
1441 } else {
1442 log.error("Unhandled config class: {}", configClass);
1443 }
Saurav Das00e553b2018-04-21 17:19:48 -07001444 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1445 MastershipEvent me = (MastershipEvent) event;
1446 DeviceId deviceId = me.subject();
1447 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1448 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1449 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1450 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1451 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1452 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan52003922018-04-05 16:31:15 -07001453 } else {
1454 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001455 }
Charles Chan52003922018-04-05 16:31:15 -07001456 } catch (Exception e) {
1457 log.error("SegmentRouting event handler thread thrown an exception: {}",
1458 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001459 }
sangho80f11cb2015-04-01 13:05:26 -07001460 }
1461 }
1462
Saurav Dase6c448a2018-01-18 12:07:33 -08001463 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001464 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001465
1466 // NOTE: Punt ARP/NDP even when the device is not configured.
1467 // Host learning without network config is required for CORD config generator.
1468 routingRulePopulator.populateIpPunts(device.id());
1469 routingRulePopulator.populateArpNdpPunts(device.id());
1470
Charles Chan319d1a22015-11-03 10:42:14 -08001471 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001472 log.warn("Device configuration unavailable. Device {} will be "
1473 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001474 return;
1475 }
Charles Chan72779502016-04-23 17:36:10 -07001476 processDeviceAddedInternal(device.id());
1477 }
1478
1479 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001480 // Irrespective of whether the local is a MASTER or not for this device,
1481 // we need to create a SR-group-handler instance. This is because in a
1482 // multi-instance setup, any instance can initiate forwarding/next-objectives
1483 // for any switch (even if this instance is a SLAVE or not even connected
1484 // to the switch). To handle this, a default-group-handler instance is necessary
1485 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001486 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1487 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001488 DefaultGroupHandler groupHandler;
1489 try {
1490 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001491 createGroupHandler(deviceId,
1492 appId,
1493 deviceConfiguration,
1494 linkService,
1495 flowObjectiveService,
1496 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001497 } catch (DeviceConfigNotFoundException e) {
1498 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1499 return;
1500 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001501 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001502 deviceId);
1503 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001504 }
Saurav Dasb149be12016-06-07 10:08:06 -07001505
Charles Chan72779502016-04-23 17:36:10 -07001506 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001507 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001508 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001509 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001510 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001511 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001512 }
Charles Chan82ab1932016-01-30 23:22:37 -08001513
Charles Chandebfea32016-10-24 14:52:01 -07001514 appCfgHandler.init(deviceId);
Charles Chan074fae62018-04-29 18:11:37 -07001515 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1516 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sangho80f11cb2015-04-01 13:05:26 -07001517 }
1518
Saurav Dasc3604f12016-03-23 11:22:49 -07001519 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001520 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001521 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001522 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001523 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001524 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001525 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001526 portNextObjStore.entrySet().stream()
1527 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001528 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001529 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001530
Saurav Dasfbe74572017-08-03 18:30:35 -07001531 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1532 if (gh != null) {
1533 gh.shutdown();
1534 }
Saurav Das62ae6792017-05-15 15:34:25 -07001535 // Note that a switch going down is associated with all of its links
1536 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001537 // while the link-downs are ignored. We cannot rely on the ordering of
1538 // events - i.e we cannot expect all link-downs to come before the
1539 // switch down - so we purge all seen-links for the switch before
1540 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001541 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001542 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001543 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001544 xConnectHandler.removeDevice(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001545
1546 // Cleanup all internal groupHandler stores for this device. Should be
1547 // done after all rerouting or rehashing has been completed
1548 groupHandlerMap.entrySet()
1549 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001550 }
1551
Saurav Das49368392018-04-23 18:42:12 -07001552 /**
1553 * Purge the destinationSet nextObjective store of entries with this device
1554 * as key. Erases app-level knowledge of hashed groups in this device.
1555 *
1556 * @param devId the device identifier
1557 */
Saurav Das00e553b2018-04-21 17:19:48 -07001558 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001559 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001560 dsNextObjStore.entrySet().stream()
1561 .filter(entry -> entry.getKey().deviceId().equals(devId))
1562 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1563 }
1564
Saurav Dasec683dc2018-04-27 18:42:30 -07001565 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001566 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1567 log.warn("Device configuration uploading. Not handling port event for"
1568 + "dev: {} port: {}", device.id(), port.number());
1569 return;
1570 }
Saurav Dasf9332192017-02-18 14:05:44 -08001571
Saurav Dasec683dc2018-04-27 18:42:30 -07001572 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1573 lastEdgePortEvent = Instant.now();
1574 }
1575
Saurav Dasf9332192017-02-18 14:05:44 -08001576 if (!mastershipService.isLocalMaster(device.id())) {
1577 log.debug("Not master for dev:{} .. not handling port updated event"
1578 + "for port {}", device.id(), port.number());
1579 return;
1580 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001581 processPortUpdated(device.id(), port);
1582 }
Saurav Dasf9332192017-02-18 14:05:44 -08001583
Saurav Dasec683dc2018-04-27 18:42:30 -07001584 /**
1585 * Adds or remove filtering rules for the given switchport. If switchport is
1586 * an edge facing port, additionally handles host probing and broadcast
1587 * rules. Must be called by local master of device.
1588 *
1589 * @param deviceId the device identifier
1590 * @param port the port to update
1591 */
1592 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001593 // first we handle filtering rules associated with the port
1594 if (port.isEnabled()) {
1595 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001596 deviceId, port.number());
1597 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001598 } else {
1599 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001600 deviceId, port.number());
1601 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001602 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001603
1604 // portUpdated calls are for ports that have gone down or up. For switch
1605 // to switch ports, link-events should take care of any re-routing or
1606 // group editing necessary for port up/down. Here we only process edge ports
1607 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001608 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001609 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1610 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1611 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001612
Saurav Das3fb28272017-03-04 16:08:47 -08001613 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001614 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001615 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001616 return;
1617 }
Saurav Das3fb28272017-03-04 16:08:47 -08001618 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001619 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001620 }
1621 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001622 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001623 }
1624 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001625 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001626 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001627 }
1628
Saurav Dasec683dc2018-04-27 18:42:30 -07001629 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001630 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001631 boolean portUp = port.isEnabled();
1632 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001633 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001634 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001635 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001636 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001637 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001638 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001639 }
1640
Saurav Dasec683dc2018-04-27 18:42:30 -07001641 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001642 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001643 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001644 } else {
1645 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001646 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001647 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001648 }
1649 }
sangho27462c62015-05-14 00:39:53 -07001650
Charles Chan8ca5a122017-10-20 16:06:55 -07001651 private void createOrUpdateDeviceConfiguration() {
1652 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001653 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001654 deviceConfiguration = new DeviceConfiguration(this);
1655 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001656 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001657 deviceConfiguration.updateConfig();
1658 }
1659 }
1660
Charles Chanfbcb8812018-04-18 18:41:05 -07001661 private void createOrUpdateDefaultRoutingHandler() {
1662 if (defaultRoutingHandler == null) {
1663 log.info("Creating new DefaultRoutingHandler");
1664 defaultRoutingHandler = new DefaultRoutingHandler(this);
1665 } else {
1666 log.info("Updating DefaultRoutingHandler");
1667 defaultRoutingHandler.update(this);
1668 }
1669 }
1670
Pier Ventreb6a7f342016-11-26 21:05:22 -08001671 /**
1672 * Registers the given connect point with the NRS, this is necessary
1673 * to receive the NDP and ARP packets from the NRS.
1674 *
1675 * @param portToRegister connect point to register
1676 */
1677 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001678 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001679 portToRegister,
1680 neighbourHandler,
1681 appId
1682 );
1683 }
1684
Charles Chan72f556a2015-10-05 17:50:33 -07001685 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001686 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001687 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001688
Charles Chanb7f75ac2016-01-11 18:28:54 -08001689 /**
1690 * Constructs the internal network config listener.
1691 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001692 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001693 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001694 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001695 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001696 }
1697
Charles Chanb7f75ac2016-01-11 18:28:54 -08001698 /**
1699 * Reads network config and initializes related data structure accordingly.
1700 */
Charles Chan873661e2017-11-30 15:37:50 -08001701 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001702 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001703
1704 // Setting handling of network configuration events completable future
1705 // The completable future is needed because of the async behaviour of the configureNetwork,
1706 // listener registration and event arrival
1707 // Enables us to buffer the events and execute them when the configure network is done.
1708 networkConfigCompletion = new CompletableFuture<>();
1709
1710 // add a small delay to absorb multiple network config added notifications
1711 if (!programmingScheduled.get()) {
1712 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1713 programmingScheduled.set(true);
1714 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1715 }
1716
Charles Chan8ca5a122017-10-20 16:06:55 -07001717 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001718
Charles Chan46fdfaf2016-11-09 20:51:44 -08001719 arpHandler = new ArpHandler(srManager);
1720 icmpHandler = new IcmpHandler(srManager);
1721 ipHandler = new IpHandler(srManager);
1722 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chanfbcb8812018-04-18 18:41:05 -07001723 createOrUpdateDefaultRoutingHandler();
Charles Chane7c61022015-10-07 14:21:45 -07001724
1725 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1726 groupHandlerMap, tunnelStore);
1727 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1728 flowObjectiveService,
1729 tunnelHandler, policyStore);
Andrea Campanella060cad82018-04-17 12:09:34 +02001730 networkConfigCompletion.complete(true);
1731
Charles Chan72779502016-04-23 17:36:10 -07001732 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001733
Charles Chane7c61022015-10-07 14:21:45 -07001734 }
1735
Charles Chan72f556a2015-10-05 17:50:33 -07001736 @Override
1737 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001738 if (mainEventExecutor == null) {
1739 return;
1740 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001741 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1742 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1743 switch (event.type()) {
1744 case CONFIG_ADDED:
1745 case CONFIG_UPDATED:
1746 case CONFIG_REMOVED:
1747 log.trace("Schedule Network Config event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001748 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1749 mainEventExecutor.execute(new InternalEventHandler(event));
1750 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001751 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001752 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001753 break;
1754 default:
1755 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001756 }
1757 }
Saurav Das261c3002017-06-13 15:35:54 -07001758
Charles Chanc4a68c32018-01-03 16:26:32 -08001759 @Override
1760 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001761 if (event.type() == CONFIG_REGISTERED ||
1762 event.type() == CONFIG_UNREGISTERED) {
1763 log.debug("Ignore event {} due to type mismatch", event);
1764 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001765 }
Saurav Dase321cff2018-02-09 17:26:45 -08001766
1767 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1768 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1769 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -08001770 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001771 log.debug("Ignore event {} due to class mismatch", event);
1772 return false;
1773 }
1774
1775 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001776 }
1777
Saurav Das261c3002017-06-13 15:35:54 -07001778 private final class ConfigChange implements Runnable {
1779 @Override
1780 public void run() {
1781 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001782 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001783 for (Device device : deviceService.getDevices()) {
1784 processDeviceAdded(device);
1785 }
1786 defaultRoutingHandler.startPopulationProcess();
1787 }
1788 }
Charles Chan72f556a2015-10-05 17:50:33 -07001789 }
Charles Chanf4586112015-11-09 16:37:23 -08001790
Charles Chan3f4aca62018-03-21 16:57:47 -07001791 private class InternalLinkListener implements LinkListener {
1792 @Override
1793 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001794 if (mainEventExecutor == null) {
1795 return;
1796 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001797 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1798 event.type() == LinkEvent.Type.LINK_UPDATED ||
1799 event.type() == LinkEvent.Type.LINK_REMOVED) {
1800 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001801 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1802 mainEventExecutor.execute(new InternalEventHandler(event));
1803 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001804 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001805 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001806 }
1807 }
1808 }
1809
1810 private class InternalDeviceListener implements DeviceListener {
1811 @Override
1812 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001813 if (mainEventExecutor == null) {
1814 return;
1815 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001816 switch (event.type()) {
1817 case DEVICE_ADDED:
1818 case PORT_UPDATED:
1819 case PORT_ADDED:
1820 case DEVICE_UPDATED:
1821 case DEVICE_AVAILABILITY_CHANGED:
1822 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001823 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1824 mainEventExecutor.execute(new InternalEventHandler(event));
1825 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001826 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001827 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001828 break;
1829 default:
1830 }
1831 }
1832 }
1833
1834 private class InternalTopologyListener implements TopologyListener {
1835 @Override
1836 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001837 if (mainEventExecutor == null) {
1838 return;
1839 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001840 switch (event.type()) {
1841 case TOPOLOGY_CHANGED:
1842 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001843 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1844 mainEventExecutor.execute(new InternalEventHandler(event));
1845 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001846 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001847 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001848 break;
1849 default:
1850 }
1851 }
1852 }
1853
Charles Chanf4586112015-11-09 16:37:23 -08001854 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001855 @Override
1856 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001857 if (hostEventExecutor == null) {
1858 return;
1859 }
Charles Chanf4586112015-11-09 16:37:23 -08001860 switch (event.type()) {
1861 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001862 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001863 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001864 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001865 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001866 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08001867 break;
1868 default:
1869 log.warn("Unsupported host event type: {}", event.type());
1870 break;
1871 }
1872 }
1873 }
1874
Charles Chanc91c8782016-03-30 17:54:24 -07001875 private class InternalMcastListener implements McastListener {
1876 @Override
1877 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001878 if (mcastEventExecutor == null) {
1879 return;
1880 }
Charles Chanc91c8782016-03-30 17:54:24 -07001881 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07001882 case SOURCES_ADDED:
1883 case SOURCES_REMOVED:
1884 case SINKS_ADDED:
1885 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07001886 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02001887 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001888 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001889 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01001890 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001891 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001892 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07001893 break;
1894 }
1895 }
1896 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001897
Charles Chandebfea32016-10-24 14:52:01 -07001898 private class InternalRouteEventListener implements RouteListener {
1899 @Override
1900 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001901 if (routeEventExecutor == null) {
1902 return;
1903 }
Charles Chandebfea32016-10-24 14:52:01 -07001904 switch (event.type()) {
1905 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07001906 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07001907 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07001908 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001909 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001910 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07001911 break;
Charles Chandebfea32016-10-24 14:52:01 -07001912 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001913 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07001914 break;
1915 }
1916 }
1917 }
Saurav Das62ae6792017-05-15 15:34:25 -07001918
Charles Chanfbcb8812018-04-18 18:41:05 -07001919 private class InternalMastershipListener implements MastershipListener {
1920 @Override
1921 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001922 if (mainEventExecutor == null) {
1923 return;
1924 }
Charles Chanfbcb8812018-04-18 18:41:05 -07001925 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07001926 case MASTER_CHANGED:
1927 log.debug("Mastership event: {}/{}", event.subject(),
1928 event.roleInfo());
1929 mainEventExecutor.execute(new InternalEventHandler(event));
1930 break;
1931 case BACKUPS_CHANGED:
1932 case SUSPENDED:
1933 default:
1934 log.debug("Mastership event type {} not handled", event.type());
1935 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07001936 }
1937 }
1938 }
1939
Saurav Das00e553b2018-04-21 17:19:48 -07001940 class InternalClusterListener implements ClusterEventListener {
1941 private Instant lastClusterEvent = Instant.EPOCH;
1942
1943 long timeSinceLastClusterEvent() {
1944 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1945 }
1946
1947 @Override
1948 public void event(ClusterEvent event) {
1949 switch (event.type()) {
1950 case INSTANCE_ACTIVATED:
1951 case INSTANCE_ADDED:
1952 case INSTANCE_READY:
1953 log.debug("Cluster event {} ignored", event.type());
1954 break;
1955 case INSTANCE_DEACTIVATED:
1956 case INSTANCE_REMOVED:
1957 log.info("** Cluster event {}", event.type());
1958 lastClusterEvent = Instant.now();
1959 break;
1960 default:
1961 break;
1962 }
1963
1964 }
1965
1966 }
1967
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001968 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1969 try {
1970 Set<Interface> intfs = conf.getInterfaces();
1971 Set<Interface> prevIntfs = prevConf.getInterfaces();
1972
1973 // Now we only handle one interface config at each port.
1974 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1975 log.warn("Interface update aborted - one at a time is allowed, " +
1976 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1977 return;
1978 }
1979
Andrea Campanella060cad82018-04-17 12:09:34 +02001980 //The system is in an incoherent state, abort
1981 if (defaultRoutingHandler == null) {
1982 log.warn("Interface update aborted, defaultRoutingHandler is null");
1983 return;
1984 }
1985
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001986 Interface intf = intfs.stream().findFirst().get();
1987 Interface prevIntf = prevIntfs.stream().findFirst().get();
1988
1989 DeviceId deviceId = intf.connectPoint().deviceId();
1990 PortNumber portNum = intf.connectPoint().port();
1991
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001992 removeSubnetConfig(prevIntf.connectPoint(),
1993 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1994 new HashSet<>(intf.ipAddressesList())));
1995
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001996 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1997 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1998 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1999 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
2000 // Update filtering objective and L2IG group bucket
2001 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
2002 } else {
2003 // RemoveVlanNative
2004 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
2005 }
2006 }
2007
2008 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
2009 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2010 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2011 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
2012 // Update filtering objective and L2IG group bucket
2013 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
2014 } else {
2015 // RemoveVlanUntagged
2016 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
2017 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002018 }
2019
2020 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2021 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002022 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2023 .filter(i -> !intf.vlanUntagged().equals(i))
2024 .filter(i -> !intf.vlanNative().equals(i))
2025 .forEach(vlanId -> updateVlanConfigInternal(
2026 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002027 }
2028
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002029 if (!intf.vlanNative().equals(VlanId.NONE)
2030 && !prevIntf.vlanNative().equals(intf.vlanNative())
2031 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2032 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2033 // Update filtering objective and L2IG group bucket
2034 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2035 } else {
2036 // AddVlanNative
2037 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2038 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002039 }
2040
2041 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2042 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002043 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2044 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2045 .filter(i -> !prevIntf.vlanNative().equals(i))
2046 .forEach(vlanId -> updateVlanConfigInternal(
2047 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002048 );
2049 }
2050
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002051 if (!intf.vlanUntagged().equals(VlanId.NONE)
2052 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2053 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2054 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2055 // Update filtering objective and L2IG group bucket
2056 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2057 } else {
2058 // AddVlanUntagged
2059 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2060 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002061 }
2062 addSubnetConfig(prevIntf.connectPoint(),
2063 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2064 new HashSet<>(prevIntf.ipAddressesList())));
2065 } catch (ConfigException e) {
2066 log.error("Error in configuration");
2067 }
2068 }
2069
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002070 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2071 VlanId vlanId, boolean pushVlan) {
2072 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2073 if (grpHandler == null) {
2074 log.warn("Failed to retrieve group handler for device {}", deviceId);
2075 return;
2076 }
2077
2078 // Update filtering objective for a single port
2079 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2080 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2081
2082 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2083 // Update L2IG bucket of the port
2084 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2085 } else {
2086 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2087 }
2088 }
2089
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002090 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2091 VlanId vlanId, boolean pushVlan, boolean install) {
2092 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2093 if (grpHandler == null) {
2094 log.warn("Failed to retrieve group handler for device {}", deviceId);
2095 return;
2096 }
2097
2098 // Update filtering objective for a single port
2099 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2100
2101 // Update filtering objective for multicast ingress port
2102 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2103
2104 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2105
2106 if (nextId != -1 && !install) {
2107 // Update next objective for a single port as an output port
2108 // Remove a single port from L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002109 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002110 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan074fae62018-04-29 18:11:37 -07002111 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2112 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002113 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2114 // only if there is no port configured on that VLAN ID
2115 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2116 // Remove broadcast forwarding rule for the VLAN
2117 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2118 // Remove L2FG for VLAN
2119 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2120 } else {
2121 // Remove L2IG of the port
2122 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2123 }
2124 } else if (install) {
2125 if (nextId != -1) {
2126 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002127 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002128 } else {
2129 // Create L2FG for VLAN
2130 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2131 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2132 }
Charles Chan074fae62018-04-29 18:11:37 -07002133 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2134 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002135 } else {
2136 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2137 }
2138 }
2139
2140 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2141 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2142 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2143
2144 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2145 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2146 .filter(intf -> !intf.connectPoint().equals(cp))
2147 .flatMap(intf -> intf.ipAddressesList().stream())
2148 .collect(Collectors.toSet());
2149 // 1. Partial subnet population
2150 // Remove routing rules for removed subnet from previous configuration,
2151 // which does not also exist in other interfaces in the same device
2152 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2153 .map(InterfaceIpAddress::subnetAddress)
2154 .collect(Collectors.toSet());
2155
2156 defaultRoutingHandler.revokeSubnet(
2157 ipPrefixSet.stream()
2158 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2159 .collect(Collectors.toSet()));
2160
2161 // 2. Interface IP punts
2162 // Remove IP punts for old Intf address
2163 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2164 .map(InterfaceIpAddress::ipAddress)
2165 .collect(Collectors.toSet());
2166 ipAddressSet.stream()
2167 .map(InterfaceIpAddress::ipAddress)
2168 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2169 .forEach(interfaceIpAddress ->
2170 routingRulePopulator.revokeSingleIpPunts(
2171 cp.deviceId(), interfaceIpAddress));
2172
2173 // 3. Host unicast routing rule
2174 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002175 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002176 }
2177
2178 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2179 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2180 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2181
2182 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2183 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2184 .filter(intf -> !intf.connectPoint().equals(cp))
2185 .flatMap(intf -> intf.ipAddressesList().stream())
2186 .collect(Collectors.toSet());
2187 // 1. Partial subnet population
2188 // Add routing rules for newly added subnet, which does not also exist in
2189 // other interfaces in the same device
2190 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2191 .map(InterfaceIpAddress::subnetAddress)
2192 .collect(Collectors.toSet());
2193
2194 defaultRoutingHandler.populateSubnet(
2195 Collections.singleton(cp),
2196 ipPrefixSet.stream()
2197 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2198 .collect(Collectors.toSet()));
2199
2200 // 2. Interface IP punts
2201 // Add IP punts for new Intf address
2202 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2203 .map(InterfaceIpAddress::ipAddress)
2204 .collect(Collectors.toSet());
2205 ipAddressSet.stream()
2206 .map(InterfaceIpAddress::ipAddress)
2207 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2208 .forEach(interfaceIpAddress ->
2209 routingRulePopulator.populateSingleIpPunts(
2210 cp.deviceId(), interfaceIpAddress));
2211
2212 // 3. Host unicast routing rule
2213 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002214 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002215 }
sangho80f11cb2015-04-01 13:05:26 -07002216}