blob: 4b7a96f796d89efbcf2c5d8c6dec1d971e51ec52 [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.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080024import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070025import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080026import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070027import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070028import org.onlab.packet.IpPrefix;
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +000029import org.onlab.packet.MacAddress;
Carmelo Cascone61004262020-01-16 13:36:02 -080030import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070031import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080032import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070033import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070034import org.onosproject.cluster.ClusterEvent;
35import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010036import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070037import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020038import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070039import org.onosproject.core.ApplicationId;
40import org.onosproject.core.CoreService;
41import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070042import org.onosproject.mastership.MastershipEvent;
43import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070044import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070045import org.onosproject.mcast.api.McastEvent;
46import org.onosproject.mcast.api.McastListener;
47import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080048import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070049import org.onosproject.net.Device;
50import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070051import org.onosproject.net.Host;
52import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070053import org.onosproject.net.Link;
54import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080055import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070056import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070057import org.onosproject.net.config.ConfigFactory;
58import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070059import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070060import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070061import org.onosproject.net.config.basics.InterfaceConfig;
62import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070063import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080064import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070065import org.onosproject.net.device.DeviceEvent;
66import org.onosproject.net.device.DeviceListener;
67import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080068import org.onosproject.net.flow.TrafficSelector;
69import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070070import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070071import org.onosproject.net.flowobjective.NextObjective;
Charles Chanf4586112015-11-09 16:37:23 -080072import org.onosproject.net.host.HostEvent;
73import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070074import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080075import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070076import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020077import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070078import org.onosproject.net.intf.Interface;
79import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080080import org.onosproject.net.link.LinkEvent;
81import org.onosproject.net.link.LinkListener;
82import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
Pier Ventre6b19e482016-11-07 16:21:04 -080096import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -070097import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanc91c8782016-03-30 17:54:24 -070098import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070099import org.onosproject.segmentrouting.grouphandler.DestinationSet;
100import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Harshada Chaundkar9204f312019-07-02 16:01:24 +0000101import org.onosproject.segmentrouting.mcast.McastFilteringObjStoreKey;
Pier Luigi69f774d2018-02-28 12:10:50 +0100102import org.onosproject.segmentrouting.mcast.McastHandler;
103import org.onosproject.segmentrouting.mcast.McastRole;
Piere99511d2018-04-19 16:47:06 +0200104import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700105import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chan12a8a842020-02-14 13:23:57 -0800106import org.onosproject.segmentrouting.phasedrecovery.api.PhasedRecoveryService;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800109import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700110import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800111import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700112import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700113import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800114import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Saurav Das261c3002017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Carmelo Cascone61004262020-01-16 13:36:02 -0800116import org.onosproject.segmentrouting.storekey.MacVlanNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700120import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700121import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700122import org.onosproject.store.service.EventuallyConsistentMap;
123import org.onosproject.store.service.EventuallyConsistentMapBuilder;
124import org.onosproject.store.service.StorageService;
125import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800126import org.osgi.service.component.ComponentContext;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700127import org.osgi.service.component.annotations.Activate;
128import org.osgi.service.component.annotations.Component;
129import org.osgi.service.component.annotations.Deactivate;
130import org.osgi.service.component.annotations.Modified;
131import org.osgi.service.component.annotations.Reference;
132import org.osgi.service.component.annotations.ReferenceCardinality;
Charles Chanb4f9cd12019-02-27 11:46:32 -0800133import org.osgi.service.component.annotations.ReferencePolicy;
sangho80f11cb2015-04-01 13:05:26 -0700134import org.slf4j.Logger;
135import org.slf4j.LoggerFactory;
136
Saurav Das00e553b2018-04-21 17:19:48 -0700137import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700138import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800139import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800140import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800141import java.util.HashSet;
142import java.util.List;
143import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800144import java.util.Optional;
145import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200146import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800147import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200148import java.util.concurrent.CopyOnWriteArrayList;
pierventrea3989be2021-01-08 16:43:17 +0100149import java.util.concurrent.ExecutionException;
Charles Chan77cdde42018-05-08 21:35:50 -0700150import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800151import java.util.concurrent.Executors;
152import java.util.concurrent.ScheduledExecutorService;
pierventrea3989be2021-01-08 16:43:17 +0100153import java.util.concurrent.ScheduledFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800154import java.util.concurrent.TimeUnit;
155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700157
Charles Chand6d25332016-02-26 22:19:52 -0800158import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800159import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700160import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800161import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700163import static org.onosproject.segmentrouting.OsgiPropertyConstants.ACTIVE_PROBING_DEFAULT;
164import static org.onosproject.segmentrouting.OsgiPropertyConstants.DEFAULT_INTERNAL_VLAN_DEFAULT;
165import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ACTIVE_PROBING;
166import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_DEFAULT_INTERNAL_VLAN;
167import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_PW_TRANSPORT_VLAN;
168import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_RESPOND_TO_UNKNOWN_HOSTS;
169import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_DOUBLE_TAGGED_HOSTS;
psneha86e60d32019-03-26 06:31:41 -0400170import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_SIMPLIFICATION;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700171import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SINGLE_HOMED_DOWN;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700172import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SYMMETRIC_PROBING;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700173import static org.onosproject.segmentrouting.OsgiPropertyConstants.PW_TRANSPORT_VLAN_DEFAULT;
174import static org.onosproject.segmentrouting.OsgiPropertyConstants.RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
175import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
psneha86e60d32019-03-26 06:31:41 -0400176import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_SIMPLIFICATION_DEFAULT;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700177import static org.onosproject.segmentrouting.OsgiPropertyConstants.SINGLE_HOMED_DOWN_DEFAULT;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700178import static org.onosproject.segmentrouting.OsgiPropertyConstants.SYMMETRIC_PROBING_DEFAULT;
Charles Chand6d25332016-02-26 22:19:52 -0800179
Charles Chanb7f75ac2016-01-11 18:28:54 -0800180/**
181 * Segment routing manager.
182 */
Ray Milkey05edbfc2018-10-23 14:23:16 -0700183@Component(
184 immediate = true,
185 service = SegmentRoutingService.class,
186 property = {
187 PROP_ACTIVE_PROBING + ":Boolean=" + ACTIVE_PROBING_DEFAULT,
188 PROP_SINGLE_HOMED_DOWN + ":Boolean=" + SINGLE_HOMED_DOWN_DEFAULT,
189 PROP_RESPOND_TO_UNKNOWN_HOSTS + ":Boolean=" + RESPOND_TO_UNKNOWN_HOSTS_DEFAULT,
190 PROP_ROUTE_DOUBLE_TAGGED_HOSTS + ":Boolean=" + ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT,
191 PROP_DEFAULT_INTERNAL_VLAN + ":Integer=" + DEFAULT_INTERNAL_VLAN_DEFAULT,
192 PROP_PW_TRANSPORT_VLAN + ":Integer=" + PW_TRANSPORT_VLAN_DEFAULT,
psneha86e60d32019-03-26 06:31:41 -0400193 PROP_SYMMETRIC_PROBING + ":Boolean=" + SYMMETRIC_PROBING_DEFAULT,
194 PROP_ROUTE_SIMPLIFICATION + ":Boolean=" + ROUTE_SIMPLIFICATION_DEFAULT
Ray Milkey05edbfc2018-10-23 14:23:16 -0700195 }
196)
sangho27462c62015-05-14 00:39:53 -0700197public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700198
Charles Chan46fdfaf2016-11-09 20:51:44 -0800199 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700200 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700201
Ray Milkey2bd24a92018-08-17 14:54:17 -0700202 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700203 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700204
Ray Milkey2bd24a92018-08-17 14:54:17 -0700205 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chancf789822019-03-22 10:04:27 -0700206 public NeighbourResolutionService neighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800207
Ray Milkey2bd24a92018-08-17 14:54:17 -0700208 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100209 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700210
Ray Milkey2bd24a92018-08-17 14:54:17 -0700211 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700212 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700213
Ray Milkey2bd24a92018-08-17 14:54:17 -0700214 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700215 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700216
Ray Milkey2bd24a92018-08-17 14:54:17 -0700217 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700218 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800219
Ray Milkey2bd24a92018-08-17 14:54:17 -0700220 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100221 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700222
Ray Milkey2bd24a92018-08-17 14:54:17 -0700223 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800224 DeviceAdminService deviceAdminService;
225
Ray Milkey2bd24a92018-08-17 14:54:17 -0700226 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800227 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700228
Ray Milkey2bd24a92018-08-17 14:54:17 -0700229 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100230 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700231
Ray Milkey2bd24a92018-08-17 14:54:17 -0700232 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800233 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700234
Ray Milkey2bd24a92018-08-17 14:54:17 -0700235 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800236 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700237
Ray Milkey2bd24a92018-08-17 14:54:17 -0700238 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100239 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700240
Ray Milkey2bd24a92018-08-17 14:54:17 -0700241 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan83163812018-01-09 13:45:07 -0800242 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700243
Ray Milkey2bd24a92018-08-17 14:54:17 -0700244 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan19b70032019-04-17 14:20:26 -0700245 public RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800246
Ray Milkey2bd24a92018-08-17 14:54:17 -0700247 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800248 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800249
Ray Milkey2bd24a92018-08-17 14:54:17 -0700250 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800251 public InterfaceService interfaceService;
252
Ray Milkey2bd24a92018-08-17 14:54:17 -0700253 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi580fd8a2018-01-16 10:47:50 +0100254 public ClusterService clusterService;
255
Ray Milkey2bd24a92018-08-17 14:54:17 -0700256 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pierdb27b8d2018-04-17 16:29:56 +0200257 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100258
Ray Milkey2bd24a92018-08-17 14:54:17 -0700259 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700260 public LeadershipService leadershipService;
261
Charles Chanb4f9cd12019-02-27 11:46:32 -0800262 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
Charles Chanb4f9cd12019-02-27 11:46:32 -0800263 policy = ReferencePolicy.DYNAMIC)
Carmelo Cascone61004262020-01-16 13:36:02 -0800264 public volatile XconnectService xconnectService;
Charles Chan8d316332018-06-19 20:31:57 -0700265
Charles Chan12a8a842020-02-14 13:23:57 -0800266 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
267 policy = ReferencePolicy.DYNAMIC)
268 volatile PhasedRecoveryService phasedRecoveryService;
269
Ray Milkey05edbfc2018-10-23 14:23:16 -0700270 /** Enable active probing to discover dual-homed hosts. */
271 boolean activeProbing = ACTIVE_PROBING_DEFAULT;
Charles Chan873661e2017-11-30 15:37:50 -0800272
Ray Milkeye96d0de2018-11-02 17:12:21 -0700273 /** Enable only send probe on the same port number of the pair device. */
274 boolean symmetricProbing = SYMMETRIC_PROBING_DEFAULT;
Mayank Tiwarif7942402018-10-29 18:27:35 -0400275
Ray Milkey05edbfc2018-10-23 14:23:16 -0700276 /** Enable administratively taking down single-homed hosts. */
277 boolean singleHomedDown = SINGLE_HOMED_DOWN_DEFAULT;
Saurav Dasec683dc2018-04-27 18:42:30 -0700278
Ray Milkey05edbfc2018-10-23 14:23:16 -0700279 /** Enable this to respond to ARP/NDP requests from unknown hosts. */
280 boolean respondToUnknownHosts = RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700281
Ray Milkey05edbfc2018-10-23 14:23:16 -0700282 /** Program flows and groups to pop and route double tagged hosts. */
283 boolean routeDoubleTaggedHosts = ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
Charles Chan4eb73bb2018-07-19 14:55:31 -0700284
Ray Milkey05edbfc2018-10-23 14:23:16 -0700285 /** internal vlan assigned by default to unconfigured ports. */
286 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700287
Ray Milkey05edbfc2018-10-23 14:23:16 -0700288 /** vlan used for transport of pseudowires between switches. */
289 private int pwTransportVlan = PW_TRANSPORT_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700290
psneha86e60d32019-03-26 06:31:41 -0400291 /** Enabling route simplification. */
292 boolean routeSimplification = ROUTE_SIMPLIFICATION_DEFAULT;
293
Charles Chandebfea32016-10-24 14:52:01 -0700294 ArpHandler arpHandler = null;
295 IcmpHandler icmpHandler = null;
296 IpHandler ipHandler = null;
297 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700298 ApplicationId appId;
299 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700300
Charles Chandebfea32016-10-24 14:52:01 -0700301 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700302 private TunnelHandler tunnelHandler = null;
303 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700304 private InternalPacketProcessor processor = null;
305 private InternalLinkListener linkListener = null;
306 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700307 private AppConfigHandler appCfgHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800308 McastHandler mcastHandler = null;
309 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800310 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800311 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800312 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800313 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100314 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800315 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700316 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
317 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700318 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100319 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700320 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700321 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200322 //Completable future for network configuration process to buffer config events handling during activation
323 private CompletableFuture<Boolean> networkConfigCompletion = null;
Ray Milkey521e4392018-11-16 15:15:14 -0800324 private final Object networkConfigCompletionLock = new Object();
Charles Chan39b75522018-04-21 00:44:29 -0700325 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700326
Charles Chan52003922018-04-05 16:31:15 -0700327 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700328 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700329
Charles Chanfbcb8812018-04-18 18:41:05 -0700330 // Handles host, route and mcast events respectively
331 private ScheduledExecutorService hostEventExecutor;
332 private ScheduledExecutorService routeEventExecutor;
333 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700334 private ExecutorService packetExecutor;
Charles Chana7601c92019-01-23 15:03:17 -0800335 ExecutorService neighborExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700336
337 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800338 /**
Saurav Das261c3002017-06-13 15:35:54 -0700339 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700340 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800341 */
Charles Chan873661e2017-11-30 15:37:50 -0800342 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700343 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800344 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700345 * Per device next objective ID store with (device id + vlanid) as key.
346 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800347 */
Charles Chan873661e2017-11-30 15:37:50 -0800348 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800349 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800350 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700351 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000352 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800353 */
Charles Chan873661e2017-11-30 15:37:50 -0800354 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800355 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800356
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700357 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000358 * Per device next objective ID store with (device id + MAC address + vlan) as key.
359 * Used to keep track of L3 unicast group for indirect hosts.
360 */
361 private EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer>
362 macVlanNextObjStore = null;
363
Saurav Das2d94d312015-11-24 23:21:05 -0800364 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
365 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700366
Saurav Das261c3002017-06-13 15:35:54 -0700367 private AtomicBoolean programmingScheduled = new AtomicBoolean();
368
Charles Chanc91c8782016-03-30 17:54:24 -0700369 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700370 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
371 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700372 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700373 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800374 public SegmentRoutingDeviceConfig createConfig() {
375 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700376 }
377 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800378
Charles Chanc91c8782016-03-30 17:54:24 -0700379 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700380 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
381 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700382 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800383 @Override
384 public SegmentRoutingAppConfig createConfig() {
385 return new SegmentRoutingAppConfig();
386 }
387 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800388
Charles Chanc91c8782016-03-30 17:54:24 -0700389 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700390 new ConfigFactory<ApplicationId, McastConfig>(
391 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700392 McastConfig.class, "multicast") {
393 @Override
394 public McastConfig createConfig() {
395 return new McastConfig();
396 }
397 };
398
Charles Chan1963f4f2016-02-18 14:22:42 -0800399 /**
400 * Segment Routing App ID.
401 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800402 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das7c305372015-10-28 12:39:42 -0700403
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700404 /**
405 * Minumum and maximum value of dummy VLAN ID to be allocated.
406 */
407 public static final int MIN_DUMMY_VLAN_ID = 2;
408 public static final int MAX_DUMMY_VLAN_ID = 4093;
409
Charles Chana7601c92019-01-23 15:03:17 -0800410 private static final int DEFAULT_POOL_SIZE = 32;
411
Saurav Dasec683dc2018-04-27 18:42:30 -0700412 Instant lastEdgePortEvent = Instant.EPOCH;
413
sangho80f11cb2015-04-01 13:05:26 -0700414 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800415 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800416 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700417
Charles Chana7601c92019-01-23 15:03:17 -0800418 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(
419 groupedThreads("onos/sr", "event-main-%d", log));
420 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(
421 groupedThreads("onos/sr", "event-host-%d", log));
422 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(
423 groupedThreads("onos/sr", "event-route-%d", log));
424 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(
425 groupedThreads("onos/sr", "event-mcast-%d", log));
426 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("onos/sr", "packet-%d", log));
427 neighborExecutor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE,
428 groupedThreads("onos/sr", "neighbor-%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700429
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700430 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700431 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700432 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700433 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700434 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700435 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700436 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700437 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700438 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700439
Charles Chan10b0fb72017-02-02 16:20:42 -0800440 log.debug("Creating EC map vlannextobjectivestore");
441 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
442 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
443 vlanNextObjStore = vlanNextObjMapBuilder
444 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700445 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700446 .withTimestampProvider((k, v) -> new WallClockTimestamp())
447 .build();
448
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000449 log.debug("Creating EC map macvlannextobjectivestore");
450 EventuallyConsistentMapBuilder<MacVlanNextObjectiveStoreKey, Integer>
451 macVlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
452 macVlanNextObjStore = macVlanNextObjMapBuilder
453 .withName("macvlannextobjectivestore")
454 .withSerializer(createSerializer())
455 .withTimestampProvider((k, v) -> new WallClockTimestamp())
456 .build();
457
Saurav Das2d94d312015-11-24 23:21:05 -0800458 log.debug("Creating EC map subnetnextobjectivestore");
459 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
460 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
461 portNextObjStore = portNextObjMapBuilder
462 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700463 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800464 .withTimestampProvider((k, v) -> new WallClockTimestamp())
465 .build();
466
sangho4a5c42a2015-05-20 22:16:38 -0700467 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
468 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700469 tunnelStore = tunnelMapBuilder
470 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700471 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700472 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700473 .build();
474
475 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
476 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700477 policyStore = policyMapBuilder
478 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700479 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700480 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700481 .build();
482
Charles Chan97979802020-02-26 15:04:44 -0800483 processor = new InternalPacketProcessor();
484 linkListener = new InternalLinkListener();
485 deviceListener = new InternalDeviceListener();
486 appCfgHandler = new AppConfigHandler(this);
487 mcastHandler = new McastHandler(this);
488 hostHandler = new HostHandler(this);
489 linkHandler = new LinkHandler(this);
490 routeHandler = new RouteHandler(this);
491 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
492 l2TunnelHandler = new DefaultL2TunnelHandler(this);
493 topologyHandler = new TopologyHandler(this);
494
Pier Luigib9632ba2017-01-12 18:14:58 -0800495 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700496 "requestInterceptsEnabled", "false", false);
Charles Chanc1909e12017-08-08 15:13:37 -0700497 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700498 "requestInterceptsEnabled", "false", false);
Charles Chan9597f8d2017-07-24 15:56:10 -0700499 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700500 "arpEnabled", "false", false);
Pier Luigi0ebeb312017-02-02 22:31:34 -0800501 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700502 "greedyLearningIpv6", "true", false);
Charles Chancf8ea472017-02-28 15:15:17 -0800503 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700504 "forceUnprovision", "true", false);
Charles Chanc7b73c72017-08-10 16:57:28 -0700505 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan0fa51db2019-04-10 17:12:20 -0700506 "distributed", "true", false);
Charles Chan804772f2017-08-14 11:42:11 -0700507 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700508 "multihomingEnabled", "true", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800509 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700510 "staleLinkAge", "15000", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800511 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700512 "allowDuplicateIps", "false", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800513 // For P4 switches
514 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700515 "fallbackFlowPollFrequency", "4", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800516 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700517 "fallbackGroupPollFrequency", "3", false);
Charles Chan873661e2017-11-30 15:37:50 -0800518 compCfgService.registerProperties(getClass());
519 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700520
Charles Chand6d25332016-02-26 22:19:52 -0800521 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700522 cfgService.registerConfigFactory(deviceConfigFactory);
523 cfgService.registerConfigFactory(appConfigFactory);
524 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800525 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200526
Charles Chan6961f222018-01-04 14:26:07 -0800527 cfgListener.configureNetwork();
528
Charles Chan82ab1932016-01-30 23:22:37 -0800529 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700530 packetService.addProcessor(processor, PacketProcessor.director(2));
531 linkService.addListener(linkListener);
532 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700533 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700534 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100535 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700536 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700537 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700538
Charles Chanc12c3d02018-03-09 15:53:44 -0800539 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800540 l2TunnelHandler.init();
541
Ray Milkey521e4392018-11-16 15:15:14 -0800542 synchronized (networkConfigCompletionLock) {
543 networkConfigCompletion.whenComplete((value, ex) -> {
544 //setting to null for easier fall through
545 networkConfigCompletion = null;
546 //process all queued events
547 queuedEvents.forEach(event -> {
548 mainEventExecutor.execute(new InternalEventHandler(event));
549 });
Andrea Campanella060cad82018-04-17 12:09:34 +0200550 });
Ray Milkey521e4392018-11-16 15:15:14 -0800551 }
Andrea Campanella060cad82018-04-17 12:09:34 +0200552
sangho80f11cb2015-04-01 13:05:26 -0700553 log.info("Started");
554 }
555
Saurav Dase6c448a2018-01-18 12:07:33 -0800556 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700557 return new KryoNamespace.Builder()
558 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700559 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800560 VlanNextObjectiveStoreKey.class,
561 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700562 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800563 NextNeighbors.class,
564 Tunnel.class,
565 DefaultTunnel.class,
566 Policy.class,
567 TunnelPolicy.class,
568 Policy.Type.class,
569 PortNextObjectiveStoreKey.class,
570 XConnectStoreKey.class,
571 L2Tunnel.class,
572 L2TunnelPolicy.class,
573 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700574 DefaultL2TunnelPolicy.class,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000575 MacVlanNextObjectiveStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700576 );
577 }
578
sangho80f11cb2015-04-01 13:05:26 -0700579 @Deactivate
580 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700581 mainEventExecutor.shutdown();
582 hostEventExecutor.shutdown();
583 routeEventExecutor.shutdown();
584 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700585 packetExecutor.shutdown();
Charles Chana7601c92019-01-23 15:03:17 -0800586 neighborExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700587
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700588 mainEventExecutor = null;
589 hostEventExecutor = null;
590 routeEventExecutor = null;
591 mcastEventExecutor = null;
592 packetExecutor = null;
Charles Chana7601c92019-01-23 15:03:17 -0800593 neighborExecutor = null;
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700594
Danny Chang44a7b952020-09-08 15:27:04 -0700595 cancelPackets();
596
Charles Chan72f556a2015-10-05 17:50:33 -0700597 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700598 cfgService.unregisterConfigFactory(deviceConfigFactory);
599 cfgService.unregisterConfigFactory(appConfigFactory);
600 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800601 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700602
Charles Chanfd48c222017-06-19 00:43:31 -0700603 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700604 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700605 linkService.removeListener(linkListener);
606 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700607 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700608 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100609 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700610 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700611 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700612
Charles Chan2e71ef32017-02-23 15:44:08 -0800613 neighbourResolutionService.unregisterNeighbourHandlers(appId);
614
sangho80f11cb2015-04-01 13:05:26 -0700615 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700616 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700617 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700618 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700619 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700620 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700621
Saurav Das261c3002017-06-13 15:35:54 -0700622 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800623 vlanNextObjStore.destroy();
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000624 macVlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700625 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700626 tunnelStore.destroy();
627 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100628
629 mcastHandler.terminate();
piercf557922019-05-17 20:47:06 +0200630 hostHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700631 log.info("Stopped");
632 }
633
Charles Chan873661e2017-11-30 15:37:50 -0800634 @Modified
635 private void modified(ComponentContext context) {
636 Dictionary<?, ?> properties = context.getProperties();
637 if (properties == null) {
638 return;
639 }
640
Ray Milkey48d10c02018-10-24 10:04:03 -0700641 String strActiveProbing = Tools.get(properties, PROP_ACTIVE_PROBING);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700642 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800643 if (expectActiveProbing != activeProbing) {
644 activeProbing = expectActiveProbing;
645 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
646 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700647
Ray Milkeye96d0de2018-11-02 17:12:21 -0700648
649 String strSymmetricProbing = Tools.get(properties, PROP_SYMMETRIC_PROBING);
650 boolean expectSymmetricProbing = Boolean.parseBoolean(strSymmetricProbing);
Mayank Tiwarif7942402018-10-29 18:27:35 -0400651 if (expectSymmetricProbing != symmetricProbing) {
652 symmetricProbing = expectSymmetricProbing;
653 log.info("{} symmetric probing", symmetricProbing ? "Enabling" : "Disabling");
654 }
655
Ray Milkey48d10c02018-10-24 10:04:03 -0700656 String strSingleHomedDown = Tools.get(properties, PROP_SINGLE_HOMED_DOWN);
Saurav Dasec683dc2018-04-27 18:42:30 -0700657 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
658 if (expectSingleHomedDown != singleHomedDown) {
659 singleHomedDown = expectSingleHomedDown;
660 log.info("{} downing of single homed hosts for lost uplinks",
661 singleHomedDown ? "Enabling" : "Disabling");
662 if (singleHomedDown && linkHandler != null) {
663 hostService.getHosts().forEach(host -> host.locations()
664 .forEach(loc -> {
665 if (interfaceService.isConfigured(loc)) {
666 linkHandler.checkUplinksForHost(loc);
667 }
668 }));
669 } else {
670 log.warn("Disabling singleHomedDown does not re-enable already "
671 + "downed ports for single-homed hosts");
672 }
673 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700674
Ray Milkey48d10c02018-10-24 10:04:03 -0700675 String strRespondToUnknownHosts = Tools.get(properties, PROP_RESPOND_TO_UNKNOWN_HOSTS);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700676 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
677 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
678 respondToUnknownHosts = expectRespondToUnknownHosts;
679 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
680 }
Charles Chan4eb73bb2018-07-19 14:55:31 -0700681
Ray Milkey48d10c02018-10-24 10:04:03 -0700682 String strRouteDoubleTaggedHosts = Tools.get(properties, PROP_ROUTE_DOUBLE_TAGGED_HOSTS);
Charles Chanfbca55e2018-07-24 16:40:35 -0700683 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
684 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
685 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
686 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan4eb73bb2018-07-19 14:55:31 -0700687
Charles Chanfbca55e2018-07-24 16:40:35 -0700688 if (routeDoubleTaggedHosts) {
Charles Chan4eb73bb2018-07-19 14:55:31 -0700689 hostHandler.populateAllDoubleTaggedHost();
690 } else {
691 hostHandler.revokeAllDoubleTaggedHost();
692 }
693 }
Saurav Das9bf49582018-08-13 15:34:26 -0700694
Ray Milkey48d10c02018-10-24 10:04:03 -0700695 String strDefaultInternalVlan = Tools.get(properties, PROP_DEFAULT_INTERNAL_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700696 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
697 if (defIntVlan != defaultInternalVlan) {
698 if (canUseVlanId(defIntVlan)) {
699 log.warn("Default internal vlan value changed from {} to {}.. "
700 + "re-programming filtering rules, but NOT any groups already "
701 + "created with the former value", defaultInternalVlan, defIntVlan);
702 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
703 defaultInternalVlan = defIntVlan;
704 routingRulePopulator
705 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
706 VlanId.vlanId((short) defIntVlan));
707 } else {
708 log.warn("Cannot change default internal vlan to unusable "
709 + "value {}", defIntVlan);
710 }
711 }
712
Ray Milkey48d10c02018-10-24 10:04:03 -0700713 String strPwTxpVlan = Tools.get(properties, PROP_PW_TRANSPORT_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700714 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
715 if (pwTxpVlan != pwTransportVlan) {
716 if (canUseVlanId(pwTxpVlan)) {
717 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
718 + "re-programming filtering rules, but NOT any groups already "
719 + "created with the former value", pwTransportVlan,
720 pwTxpVlan);
721 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
722 pwTransportVlan = pwTxpVlan;
723 routingRulePopulator
724 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
725 VlanId.vlanId((short) pwTxpVlan));
726 } else {
727 log.warn("Cannot change pseudowire transport vlan to unusable "
728 + "value {}", pwTxpVlan);
729 }
730 }
731
psneha86e60d32019-03-26 06:31:41 -0400732 String strRouteSimplification = Tools.get(properties, PROP_ROUTE_SIMPLIFICATION);
733 boolean expectRouteSimplification = Boolean.parseBoolean(strRouteSimplification);
734 if (expectRouteSimplification != routeSimplification) {
735 routeSimplification = expectRouteSimplification;
736 log.info("{} route simplification", routeSimplification ? "Enabling" : "Disabling");
737 }
738
Saurav Das9bf49582018-08-13 15:34:26 -0700739 }
740
741 /**
Danny Chang44a7b952020-09-08 15:27:04 -0700742 * Removes all packet requests.
743 */
744 private void cancelPackets() {
745 if (routingRulePopulator == null) {
746 return;
747 }
748 log.info("Removing packet requests.");
749 routingRulePopulator.revokePacketsPunts();
750 }
751
752 /**
Saurav Das9bf49582018-08-13 15:34:26 -0700753 * Returns true if given vlan id is not being used in the system currently,
754 * either as one of the default system wide vlans or as one of the
755 * configured interface vlans.
756 *
757 * @param vlanId given vlan id
758 * @return true if vlan is not currently in use
759 */
760 public boolean canUseVlanId(int vlanId) {
761 if (vlanId >= 4095 || vlanId <= 1) {
762 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
763 vlanId);
764 return false;
765 }
766
767 VlanId vid = VlanId.vlanId((short) vlanId);
768 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
769 log.warn("Vlan id {} value is already in use system-wide. "
770 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
771 getDefaultInternalVlan(), getPwTransportVlan());
772 return false;
773 }
774
775 if (interfaceService.inUse(vid)) {
776 log.warn("Vlan id {} value is already in use on a configured "
777 + "interface in the system", vlanId);
778 return false;
779 }
780 return true;
781 }
782
pierventre4f68ffa2021-03-09 22:52:14 +0100783 @Override
Saurav Das9bf49582018-08-13 15:34:26 -0700784 public VlanId getDefaultInternalVlan() {
785 return VlanId.vlanId((short) defaultInternalVlan);
786 }
787
788 /**
789 * Returns the Vlan id used to transport pseudowire traffic across the
790 * network.
791 *
792 * @return the pseudowire transport vlan id
793 */
794 public VlanId getPwTransportVlan() {
795 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan873661e2017-11-30 15:37:50 -0800796 }
797
sangho27462c62015-05-14 00:39:53 -0700798 @Override
799 public List<Tunnel> getTunnels() {
800 return tunnelHandler.getTunnels();
801 }
802
803 @Override
sanghobd812f82015-06-29 14:58:47 -0700804 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
805 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700806 }
807
808 @Override
sanghobd812f82015-06-29 14:58:47 -0700809 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700810 for (Policy policy: policyHandler.getPolicies()) {
811 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
812 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
813 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
814 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700815 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700816 }
817 }
818 }
sanghobd812f82015-06-29 14:58:47 -0700819 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700820 }
821
822 @Override
sanghobd812f82015-06-29 14:58:47 -0700823 public PolicyHandler.Result removePolicy(Policy policy) {
824 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700825 }
826
827 @Override
sanghobd812f82015-06-29 14:58:47 -0700828 public PolicyHandler.Result createPolicy(Policy policy) {
829 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700830 }
831
832 @Override
833 public List<Policy> getPolicies() {
834 return policyHandler.getPolicies();
835 }
836
Saurav Das07c74602016-04-27 18:35:50 -0700837 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700838 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
839 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700840 }
841
842 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800843 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700844 return l2TunnelHandler.getL2Tunnels();
845 }
846
847 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800848 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700849 return l2TunnelHandler.getL2Policies();
850 }
851
Saurav Dasdebcf882018-04-06 20:16:01 -0700852 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700853 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700854 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
855
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700856 // get both added and pending pseudowires
857 List<L2TunnelDescription> pseudowires = new ArrayList<>();
858 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
859 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700860 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700861
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700862 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
863
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700864 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
865 L2TunnelHandler.Result res;
866 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
867 res = addPseudowire(pw);
868 if (res != L2TunnelHandler.Result.SUCCESS) {
869 log.error("Pseudowire with id {} can not be instantiated !", res);
870 retRes = res;
871 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700872 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700873
874 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700875 }
876
877 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800878 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700879 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700880 }
881
882 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800883 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700884 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700885 }
886
887 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700888 public void rerouteNetwork() {
889 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700890 }
891
Charles Chand7844e52016-10-20 17:02:44 -0700892 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800893 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
894 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800895 deviceConfiguration.getRouters().forEach(device ->
896 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700897 return deviceSubnetMap;
898 }
899
Saurav Das62ae6792017-05-15 15:34:25 -0700900
901 @Override
902 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
903 if (defaultRoutingHandler != null) {
904 return defaultRoutingHandler.getCurrentEmcpSpgMap();
905 } else {
906 return null;
907 }
908 }
909
910 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700911 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das261c3002017-06-13 15:35:54 -0700912 if (dsNextObjStore != null) {
913 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700914 } else {
915 return ImmutableMap.of();
916 }
917 }
918
Saurav Dasfbe74572017-08-03 18:30:35 -0700919 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700920 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
921 if (vlanNextObjStore != null) {
922 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
923 } else {
924 return ImmutableMap.of();
925 }
926 }
927
928 @Override
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000929 public ImmutableMap<MacVlanNextObjectiveStoreKey, Integer> getMacVlanNextObjStore() {
930 if (macVlanNextObjStore != null) {
931 return ImmutableMap.copyOf(macVlanNextObjStore.entrySet());
932 } else {
933 return ImmutableMap.of();
934 }
935 }
936
937 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700938 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
939 if (portNextObjStore != null) {
940 return ImmutableMap.copyOf(portNextObjStore.entrySet());
941 } else {
942 return ImmutableMap.of();
943 }
944 }
945
946 @Override
947 public ImmutableMap<String, NextObjective> getPwInitNext() {
948 if (l2TunnelHandler != null) {
949 return l2TunnelHandler.getInitNext();
950 } else {
951 return ImmutableMap.of();
952 }
953 }
954
955 @Override
956 public ImmutableMap<String, NextObjective> getPwTermNext() {
957 if (l2TunnelHandler != null) {
958 return l2TunnelHandler.getTermNext();
959 } else {
960 return ImmutableMap.of();
961 }
962 }
963
964 @Override
965 public void invalidateNextObj(int nextId) {
966 if (dsNextObjStore != null) {
967 dsNextObjStore.entrySet().forEach(e -> {
968 if (e.getValue().nextId() == nextId) {
969 dsNextObjStore.remove(e.getKey());
970 }
971 });
972 }
973 if (vlanNextObjStore != null) {
974 vlanNextObjStore.entrySet().forEach(e -> {
975 if (e.getValue() == nextId) {
976 vlanNextObjStore.remove(e.getKey());
977 }
978 });
979 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000980 if (macVlanNextObjStore != null) {
981 macVlanNextObjStore.entrySet().forEach(e -> {
982 if (e.getValue() == nextId) {
983 macVlanNextObjStore.remove(e.getKey());
984 }
985 });
986 }
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700987 if (portNextObjStore != null) {
988 portNextObjStore.entrySet().forEach(e -> {
989 if (e.getValue() == nextId) {
990 portNextObjStore.remove(e.getKey());
991 }
992 });
993 }
994 if (mcastHandler != null) {
995 mcastHandler.removeNextId(nextId);
996 }
997 if (l2TunnelHandler != null) {
998 l2TunnelHandler.removeNextId(nextId);
999 }
1000 if (xconnectService != null) {
1001 xconnectService.removeNextId(nextId);
1002 }
1003 }
1004
1005 @Override
Saurav Dasfbe74572017-08-03 18:30:35 -07001006 public void verifyGroups(DeviceId id) {
1007 DefaultGroupHandler gh = groupHandlerMap.get(id);
1008 if (gh != null) {
1009 gh.triggerBucketCorrector();
1010 }
1011 }
1012
Saurav Das6430f412018-01-25 09:49:01 -08001013 @Override
1014 public ImmutableMap<Link, Boolean> getSeenLinks() {
1015 return linkHandler.getSeenLinks();
1016 }
1017
1018 @Override
1019 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
1020 return linkHandler.getDownedPorts();
1021 }
1022
Pier Luigi0f9635b2018-01-15 18:06:43 +01001023 @Override
1024 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -07001025 return mcastHandler.getNextIds(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +01001026 }
1027
1028 @Override
Piere99511d2018-04-19 16:47:06 +02001029 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
1030 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
1031 }
1032
1033 @Override
Pier71c55772018-04-17 17:25:22 +02001034 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
1035 ConnectPoint sourcecp) {
1036 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
1037 }
1038
1039 @Override
Pierdb27b8d2018-04-17 16:29:56 +02001040 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
1041 return mcastHandler.getMcastLeaders(mcastIp);
1042 }
1043
Charles Chanb13e0702018-04-17 18:56:53 -07001044 @Override
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001045 public Map<DeviceId, List<McastFilteringObjStoreKey>> getMcastFilters() {
1046 return mcastHandler.getMcastFilters();
1047 }
1048
1049 @Override
Charles Chanb13e0702018-04-17 18:56:53 -07001050 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
1051 return defaultRoutingHandler == null ? ImmutableMap.of() :
1052 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
1053 }
1054
1055 @Override
1056 public Map<DeviceId, Boolean> getShouldProgramCache() {
1057 return defaultRoutingHandler == null ? ImmutableMap.of() :
1058 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
1059 }
1060
Charles Chan8d316332018-06-19 20:31:57 -07001061 @Override
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301062 public boolean shouldProgram(DeviceId deviceId) {
1063 return defaultRoutingHandler.shouldProgram(deviceId);
1064 }
1065
1066 @Override
Charles Chan12a8a842020-02-14 13:23:57 -08001067 public boolean isRoutingStable() {
1068 return defaultRoutingHandler.isRoutingStable();
1069 }
1070
1071 @Override
1072 public void initHost(DeviceId deviceId) {
1073 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1074 }
1075
1076 @Override
1077 public void initRoute(DeviceId deviceId) {
1078 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
1079 }
1080
1081 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -07001082 public ApplicationId appId() {
1083 return appId;
1084 }
1085
1086 /**
1087 * Returns the device configuration.
1088 *
1089 * @return device configuration
1090 */
1091 public DeviceConfiguration deviceConfiguration() {
1092 return deviceConfiguration;
1093 }
1094
1095 /**
Saurav Das261c3002017-06-13 15:35:54 -07001096 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -07001097 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001098 *
1099 * @return next objective ID store
1100 */
Saurav Das261c3002017-06-13 15:35:54 -07001101 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1102 dsNextObjStore() {
1103 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -07001104 }
1105
1106 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001107 * Per device next objective ID store with (device id + vlanid) as key.
1108 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001109 *
1110 * @return vlan next object store
1111 */
1112 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1113 return vlanNextObjStore;
1114 }
1115
1116 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001117 * Per device next objective ID store with (device id + MAC address + vlan) as key.
1118 * Used to keep track on L3 Unicast group information for indirect hosts.
1119 *
1120 * @return mac vlan next object store
1121 */
1122 public EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer> macVlanNextObjStore() {
1123 return macVlanNextObjStore;
1124 }
1125
1126 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001127 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001128 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Ray Milkeyb85de082017-04-05 09:42:04 -07001129 *
1130 * @return port next object store.
1131 */
1132 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1133 return portNextObjStore;
1134 }
1135
1136 /**
Saurav Das261c3002017-06-13 15:35:54 -07001137 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1138 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -07001139 *
1140 * @return MPLS-ECMP value
1141 */
1142 public boolean getMplsEcmp() {
1143 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1144 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1145 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1146 }
1147
1148 /**
sangho80f1f892015-05-19 11:57:42 -07001149 * Returns the tunnel object with the tunnel ID.
1150 *
1151 * @param tunnelId Tunnel ID
1152 * @return Tunnel reference
1153 */
sangho27462c62015-05-14 00:39:53 -07001154 public Tunnel getTunnel(String tunnelId) {
1155 return tunnelHandler.getTunnel(tunnelId);
1156 }
1157
Charles Chan8d316332018-06-19 20:31:57 -07001158 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +01001159 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -07001160 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1161 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -07001162 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1163 }
1164
Charles Chan8d316332018-06-19 20:31:57 -07001165 @Override
1166 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001167 SegmentRoutingDeviceConfig deviceConfig =
1168 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1169 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1170 }
Charles Chan8d316332018-06-19 20:31:57 -07001171
1172 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -07001173 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001174 SegmentRoutingDeviceConfig deviceConfig =
1175 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1176 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1177 }
1178
Charles Chan12a8a842020-02-14 13:23:57 -08001179 @Override
1180 public Set<PortNumber> getInfraPorts(DeviceId deviceId) {
1181 return deviceService.getPorts(deviceId).stream()
1182 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1183 .filter(cp -> interfaceService.getInterfacesByPort(cp).isEmpty())
1184 .map(ConnectPoint::port)
1185 .collect(Collectors.toSet());
1186 }
1187
1188 @Override
1189 public Set<PortNumber> getEdgePorts(DeviceId deviceId) {
1190 return deviceService.getPorts(deviceId).stream()
1191 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1192 .filter(cp -> !interfaceService.getInterfacesByPort(cp).isEmpty() &&
1193 !cp.port().equals(getPairLocalPort(deviceId).orElse(null)))
1194 .map(ConnectPoint::port)
1195 .collect(Collectors.toSet());
1196 }
1197
pierventre30368ab2021-02-24 23:23:22 +01001198 @Override
1199 public List<DeviceId> getEdgeDeviceIds() {
1200 return deviceConfiguration.getEdgeDeviceIds();
1201 }
1202
pierventre4f68ffa2021-03-09 22:52:14 +01001203 @Override
1204 public MacAddress getDeviceMacAddress(DeviceId deviceId) throws DeviceConfigNotFoundException {
1205 return deviceConfiguration.getDeviceMac(deviceId);
1206 }
1207
Charles Chan3ed34d82017-06-22 18:03:14 -07001208 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -07001209 * Returns locations of given resolved route.
1210 *
1211 * @param resolvedRoute resolved route
1212 * @return locations of nexthop. Might be empty if next hop is not found
1213 */
Charles Chan19b70032019-04-17 14:20:26 -07001214 public Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
Charles Chanf0ae41e2017-08-23 13:55:39 -07001215 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1216 return Optional.ofNullable(hostService.getHost(hostId))
1217 .map(Host::locations).orElse(Sets.newHashSet())
1218 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1219 }
1220
1221 /**
Charles Chan90772a72017-02-08 15:52:08 -08001222 * Returns vlan port map of given device.
1223 *
1224 * @param deviceId device id
1225 * @return vlan-port multimap
1226 */
1227 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1228 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1229
1230 interfaceService.getInterfaces().stream()
1231 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1232 .forEach(intf -> {
1233 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -07001234 intf.vlanTagged().forEach(vlanTagged ->
1235 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1236 );
Charles Chan90772a72017-02-08 15:52:08 -08001237 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1238 });
1239 vlanPortMap.removeAll(VlanId.NONE);
1240
1241 return vlanPortMap;
1242 }
1243
1244 /**
Charles Chan10b0fb72017-02-02 16:20:42 -08001245 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -08001246 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -07001247 *
1248 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -08001249 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -08001250 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -07001251 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001252 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -07001253 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -08001254 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1255 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -07001256 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -08001257 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -08001258 + "device {} not found", deviceId);
1259 return -1;
1260 }
1261 }
1262
1263 /**
1264 * Returns the next objective ID for the given portNumber, given the treatment.
1265 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -07001266 * would result in different objectives. If the next object does not exist,
1267 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -08001268 *
1269 * @param deviceId Device ID
1270 * @param portNum port number on device for which NextObjective is queried
1271 * @param treatment the actions to apply on the packets (should include outport)
1272 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -07001273 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -07001274 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -08001275 */
1276 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1277 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -07001278 TrafficSelector meta,
1279 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -08001280 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1281 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -07001282 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -08001283 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -08001284 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1285 + " not found", deviceId);
1286 return -1;
1287 }
1288 }
1289
Saurav Das62ae6792017-05-15 15:34:25 -07001290 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001291 * Returns the next Objective ID for the given mac and vlan, given the treatment.
1292 * There could be multiple different treatments to the same outport, which
1293 * would result in different objectives. If the next object does not exist,
1294 * and should be created, a new one is created and its id is returned.
1295 *
1296 * @param deviceId Device ID
1297 * @param macAddr mac of host for which Next ID is required.
1298 * @param vlanId vlan of host for which Next ID is required.
Ruchi Sahota07869322019-05-09 17:26:14 -04001299 * @param port port with which to create the Next Obj.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001300 * @param createIfMissing true if a next object should be created if not found
1301 * @return next objective ID or -1 if an error occurred during retrieval or creation
1302 */
1303 public int getMacVlanNextObjectiveId(DeviceId deviceId, MacAddress macAddr, VlanId vlanId,
Ruchi Sahota07869322019-05-09 17:26:14 -04001304 PortNumber port, boolean createIfMissing) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001305 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1306 if (ghdlr != null) {
Ruchi Sahota07869322019-05-09 17:26:14 -04001307 return ghdlr.getMacVlanNextObjectiveId(macAddr, vlanId, port, createIfMissing);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001308 } else {
1309 log.warn("getMacVlanNextObjectiveId query - groupHandler for device {}"
1310 + " not found", deviceId);
1311 return -1;
1312 }
1313 }
1314
1315 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001316 * Updates the next objective for the given nextId .
1317 *
1318 * @param deviceId Device ID
1319 * @param hostMac mac of host for which Next obj is to be updated.
1320 * @param hostVlanId vlan of host for which Next obj is to be updated.
1321 * @param port port with which to update the Next Obj.
1322 * @param nextId of Next Obj which needs to be updated.
1323 */
1324 public void updateMacVlanTreatment(DeviceId deviceId, MacAddress hostMac,
pierventrea3989be2021-01-08 16:43:17 +01001325 VlanId hostVlanId, PortNumber port, int nextId) {
pierf0e37ec2019-11-26 11:48:48 +01001326 // Check if we are the king of this device
1327 // just one instance should perform this update
1328 if (!defaultRoutingHandler.shouldProgram(deviceId)) {
1329 log.debug("This instance is not handling the routing towards the "
1330 + "device {}", deviceId);
1331 return;
1332 }
1333 // Get the handler and perform the update
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001334 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1335 if (ghdlr != null) {
1336 ghdlr.updateL3UcastGroupBucket(hostMac, hostVlanId, port, nextId);
1337 } else {
1338 log.warn("updateL3UcastGroupBucket query - groupHandler for device {}"
1339 + " not found", deviceId);
1340 }
1341 }
1342
1343
1344 /**
Saurav Das62ae6792017-05-15 15:34:25 -07001345 * Returns the group handler object for the specified device id.
1346 *
1347 * @param devId the device identifier
1348 * @return the groupHandler object for the device id, or null if not found
1349 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001350 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001351 return groupHandlerMap.get(devId);
1352 }
1353
1354 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001355 * Returns the default routing handler object.
1356 *
1357 * @return the default routing handler object
1358 */
1359 public DefaultRoutingHandler getRoutingHandler() {
1360 return defaultRoutingHandler;
1361 }
1362
sangho80f11cb2015-04-01 13:05:26 -07001363 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001364 @Override
1365 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001366 packetExecutor.execute(() -> processPacketInternal(context));
1367 }
sangho80f11cb2015-04-01 13:05:26 -07001368
Charles Chan77cdde42018-05-08 21:35:50 -07001369 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001370 if (context.isHandled()) {
1371 return;
1372 }
1373
1374 InboundPacket pkt = context.inPacket();
1375 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001376
1377 if (ethernet == null) {
1378 return;
1379 }
1380
Saurav Das261c3002017-06-13 15:35:54 -07001381 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1382 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001383 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001384 log.warn("Received unexpected ARP packet on {}",
1385 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001386 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001387 return;
sangho80f11cb2015-04-01 13:05:26 -07001388 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001389 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1390 //ipHandler.addToPacketBuffer(ipv4Packet);
1391 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1392 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001393 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001394 // NOTE: We don't support IP learning at this moment so this
1395 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001396 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001397 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001398 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1399 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001400 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001401 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001402 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1403 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1404 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1405 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1406 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1407 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001408 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001409 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001410 }
1411 } else {
1412 // NOTE: We don't support IP learning at this moment so this
1413 // is not necessary. Also it causes duplication of DHCPv6 packets.
1414 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1415 }
sangho80f11cb2015-04-01 13:05:26 -07001416 }
1417 }
1418 }
1419
sangho80f11cb2015-04-01 13:05:26 -07001420 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001421 private Event event;
1422
1423 InternalEventHandler(Event event) {
1424 this.event = event;
1425 }
1426
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001427 @Override
sangho80f11cb2015-04-01 13:05:26 -07001428 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001429 try {
1430 // TODO We should also change SR routing and PW to listen to TopologyEvents
1431 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1432 event.type() == LinkEvent.Type.LINK_UPDATED) {
1433 linkHandler.processLinkAdded((Link) event.subject());
1434 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1435 linkHandler.processLinkRemoved((Link) event.subject());
1436 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1437 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1438 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1439 DeviceId deviceId = ((Device) event.subject()).id();
1440 if (deviceService.isAvailable(deviceId)) {
1441 log.info("** DEVICE UP Processing device event {} "
1442 + "for available device {}",
1443 event.type(), ((Device) event.subject()).id());
1444 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001445 } else {
Charles Chanb8f3af52018-08-29 21:21:51 -07001446 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1447 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1448 // The device will later on being marked as available once the pipeline is pushed
1449 // to the device.
1450 log.info("** DEVICE ADDED but unavailable. Ignore");
1451 return;
1452 }
Charles Chan52003922018-04-05 16:31:15 -07001453 log.info(" ** DEVICE DOWN Processing device event {}"
1454 + " for unavailable device {}",
1455 event.type(), ((Device) event.subject()).id());
1456 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001457 }
Charles Chan52003922018-04-05 16:31:15 -07001458 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1459 // typically these calls come when device is added first time
1460 // so port filtering rules are handled at the device_added event.
1461 // port added calls represent all ports on the device,
1462 // enabled or not.
1463 log.trace("** PORT ADDED {}/{} -> {}",
1464 ((DeviceEvent) event).subject().id(),
1465 ((DeviceEvent) event).port().number(),
1466 event.type());
1467 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1468 // these calls happen for every subsequent event
1469 // ports enabled, disabled, switch goes away, comes back
1470 log.info("** PORT UPDATED {}/{} -> {}",
1471 event.subject(),
1472 ((DeviceEvent) event).port(),
1473 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001474 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001475 ((DeviceEvent) event).port());
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001476 mcastHandler.processPortUpdate(((Device) event.subject()),
1477 ((DeviceEvent) event).port());
Charles Chan52003922018-04-05 16:31:15 -07001478 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1479 // Process topology event, needed for all modules relying on
1480 // topology service for path computation
1481 TopologyEvent topologyEvent = (TopologyEvent) event;
1482 log.info("Processing topology event {}, topology age {}, reasons {}",
1483 event.type(), topologyEvent.subject().time(),
1484 topologyEvent.reasons().size());
1485 topologyHandler.processTopologyChange(topologyEvent.reasons());
1486 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1487 hostHandler.processHostAddedEvent((HostEvent) event);
1488 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1489 hostHandler.processHostMovedEvent((HostEvent) event);
1490 routeHandler.processHostMovedEvent((HostEvent) event);
Charles Chana2ccb582019-11-25 09:47:22 -08001491 } else if (event.type() == HostEvent.Type.HOST_AUX_MOVED) {
1492 hostHandler.processHostMovedEvent((HostEvent) event);
1493 // TODO RouteHandler also needs to process this event in order to
1494 // support nexthops that has auxLocations
Charles Chan52003922018-04-05 16:31:15 -07001495 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1496 hostHandler.processHostRemovedEvent((HostEvent) event);
1497 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1498 hostHandler.processHostUpdatedEvent((HostEvent) event);
1499 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1500 routeHandler.processRouteAdded((RouteEvent) event);
1501 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1502 routeHandler.processRouteUpdated((RouteEvent) event);
1503 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1504 routeHandler.processRouteRemoved((RouteEvent) event);
1505 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1506 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1507 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1508 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1509 event.type() == McastEvent.Type.SINKS_ADDED ||
1510 event.type() == McastEvent.Type.SINKS_REMOVED ||
1511 event.type() == McastEvent.Type.ROUTE_ADDED ||
1512 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1513 mcastHandler.processMcastEvent((McastEvent) event);
1514 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1515 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1516 Class configClass = netcfgEvent.configClass();
1517 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1518 appCfgHandler.processAppConfigAdded(netcfgEvent);
1519 log.info("App config event .. configuring network");
1520 cfgListener.configureNetwork();
1521 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1522 log.info("Segment Routing Device Config added for {}", event.subject());
1523 cfgListener.configureNetwork();
Charles Chan52003922018-04-05 16:31:15 -07001524 } else if (configClass.equals(InterfaceConfig.class)) {
1525 log.info("Interface Config added for {}", event.subject());
1526 cfgListener.configureNetwork();
1527 } else {
1528 log.error("Unhandled config class: {}", configClass);
1529 }
1530 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1531 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1532 Class configClass = netcfgEvent.configClass();
1533 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1534 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1535 log.info("App config event .. configuring network");
1536 cfgListener.configureNetwork();
1537 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1538 log.info("Segment Routing Device Config updated for {}", event.subject());
1539 createOrUpdateDeviceConfiguration();
Charles Chan52003922018-04-05 16:31:15 -07001540 } else if (configClass.equals(InterfaceConfig.class)) {
1541 log.info("Interface Config updated for {}", event.subject());
1542 createOrUpdateDeviceConfiguration();
1543 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1544 (InterfaceConfig) netcfgEvent.prevConfig().get());
1545 } else {
1546 log.error("Unhandled config class: {}", configClass);
1547 }
1548 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1549 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1550 Class configClass = netcfgEvent.configClass();
1551 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1552 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1553 log.info("App config event .. configuring network");
1554 cfgListener.configureNetwork();
1555 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1556 // TODO Handle sr device config removal
1557 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
Charles Chan52003922018-04-05 16:31:15 -07001558 } else if (configClass.equals(InterfaceConfig.class)) {
1559 // TODO Handle interface removal
1560 log.info("InterfaceConfig removal is not handled in current implementation");
1561 } else {
1562 log.error("Unhandled config class: {}", configClass);
1563 }
Saurav Das00e553b2018-04-21 17:19:48 -07001564 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1565 MastershipEvent me = (MastershipEvent) event;
1566 DeviceId deviceId = me.subject();
1567 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1568 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1569 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1570 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1571 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1572 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan52003922018-04-05 16:31:15 -07001573 } else {
1574 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001575 }
Charles Chan52003922018-04-05 16:31:15 -07001576 } catch (Exception e) {
1577 log.error("SegmentRouting event handler thread thrown an exception: {}",
1578 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001579 }
sangho80f11cb2015-04-01 13:05:26 -07001580 }
1581 }
1582
Saurav Dase6c448a2018-01-18 12:07:33 -08001583 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001584 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001585
1586 // NOTE: Punt ARP/NDP even when the device is not configured.
1587 // Host learning without network config is required for CORD config generator.
1588 routingRulePopulator.populateIpPunts(device.id());
1589 routingRulePopulator.populateArpNdpPunts(device.id());
1590
Charles Chan319d1a22015-11-03 10:42:14 -08001591 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001592 log.warn("Device configuration unavailable. Device {} will be "
1593 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001594 return;
1595 }
Charles Chan72779502016-04-23 17:36:10 -07001596 processDeviceAddedInternal(device.id());
1597 }
1598
1599 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001600 // Irrespective of whether the local is a MASTER or not for this device,
1601 // we need to create a SR-group-handler instance. This is because in a
1602 // multi-instance setup, any instance can initiate forwarding/next-objectives
1603 // for any switch (even if this instance is a SLAVE or not even connected
1604 // to the switch). To handle this, a default-group-handler instance is necessary
1605 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001606 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1607 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001608 DefaultGroupHandler groupHandler;
1609 try {
1610 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001611 createGroupHandler(deviceId,
1612 appId,
1613 deviceConfiguration,
1614 linkService,
1615 flowObjectiveService,
1616 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001617 } catch (DeviceConfigNotFoundException e) {
1618 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1619 return;
1620 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001621 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001622 deviceId);
1623 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001624 }
Saurav Dasb149be12016-06-07 10:08:06 -07001625
Charles Chan72779502016-04-23 17:36:10 -07001626 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001627 defaultRoutingHandler.populatePortAddressingRules(deviceId);
pierf331a492020-01-07 15:39:39 +01001628 defaultRoutingHandler.purgeSeenBeforeRoutes(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001629 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001630 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001631 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan12a8a842020-02-14 13:23:57 -08001632 phasedRecoveryService.init(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001633 }
Charles Chan82ab1932016-01-30 23:22:37 -08001634
Charles Chandebfea32016-10-24 14:52:01 -07001635 appCfgHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001636 }
1637
Saurav Dasc3604f12016-03-23 11:22:49 -07001638 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001639 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001640 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001641 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001642 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001643 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001644 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001645 macVlanNextObjStore.entrySet().stream()
1646 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1647 .forEach(entry -> macVlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001648 portNextObjStore.entrySet().stream()
1649 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001650 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001651 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001652
Saurav Dasfbe74572017-08-03 18:30:35 -07001653 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1654 if (gh != null) {
1655 gh.shutdown();
1656 }
Saurav Das62ae6792017-05-15 15:34:25 -07001657 // Note that a switch going down is associated with all of its links
1658 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001659 // while the link-downs are ignored. We cannot rely on the ordering of
1660 // events - i.e we cannot expect all link-downs to come before the
1661 // switch down - so we purge all seen-links for the switch before
1662 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001663 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001664 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001665 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001666
1667 // Cleanup all internal groupHandler stores for this device. Should be
1668 // done after all rerouting or rehashing has been completed
1669 groupHandlerMap.entrySet()
1670 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Charles Chan12a8a842020-02-14 13:23:57 -08001671
1672 phasedRecoveryService.reset(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001673 }
1674
Saurav Das49368392018-04-23 18:42:12 -07001675 /**
1676 * Purge the destinationSet nextObjective store of entries with this device
1677 * as key. Erases app-level knowledge of hashed groups in this device.
1678 *
1679 * @param devId the device identifier
1680 */
Saurav Das00e553b2018-04-21 17:19:48 -07001681 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001682 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001683 dsNextObjStore.entrySet().stream()
1684 .filter(entry -> entry.getKey().deviceId().equals(devId))
1685 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1686 }
1687
Saurav Dasec683dc2018-04-27 18:42:30 -07001688 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001689 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1690 log.warn("Device configuration uploading. Not handling port event for"
1691 + "dev: {} port: {}", device.id(), port.number());
1692 return;
1693 }
Saurav Dasf9332192017-02-18 14:05:44 -08001694
Saurav Dasec683dc2018-04-27 18:42:30 -07001695 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1696 lastEdgePortEvent = Instant.now();
1697 }
1698
Saurav Dasf9332192017-02-18 14:05:44 -08001699 if (!mastershipService.isLocalMaster(device.id())) {
1700 log.debug("Not master for dev:{} .. not handling port updated event"
1701 + "for port {}", device.id(), port.number());
1702 return;
1703 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001704 processPortUpdated(device.id(), port);
1705 }
Saurav Dasf9332192017-02-18 14:05:44 -08001706
Saurav Dasec683dc2018-04-27 18:42:30 -07001707 /**
1708 * Adds or remove filtering rules for the given switchport. If switchport is
1709 * an edge facing port, additionally handles host probing and broadcast
1710 * rules. Must be called by local master of device.
1711 *
1712 * @param deviceId the device identifier
1713 * @param port the port to update
1714 */
1715 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001716 // first we handle filtering rules associated with the port
1717 if (port.isEnabled()) {
1718 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001719 deviceId, port.number());
1720 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001721 } else {
1722 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001723 deviceId, port.number());
1724 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001725 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001726
1727 // portUpdated calls are for ports that have gone down or up. For switch
1728 // to switch ports, link-events should take care of any re-routing or
1729 // group editing necessary for port up/down. Here we only process edge ports
1730 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001731 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001732 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1733 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1734 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001735
Saurav Das3fb28272017-03-04 16:08:47 -08001736 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001737 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001738 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001739 return;
1740 }
Saurav Das3fb28272017-03-04 16:08:47 -08001741 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001742 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001743 }
1744 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001745 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001746 }
1747 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001748 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001749 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001750 }
1751
Saurav Dasec683dc2018-04-27 18:42:30 -07001752 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001753 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001754 boolean portUp = port.isEnabled();
1755 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001756 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001757 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001758 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001759 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001760 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001761 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001762 }
1763
Saurav Dasec683dc2018-04-27 18:42:30 -07001764 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001765 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001766 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001767 } else {
1768 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001769 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001770 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001771 }
1772 }
sangho27462c62015-05-14 00:39:53 -07001773
Charles Chan8ca5a122017-10-20 16:06:55 -07001774 private void createOrUpdateDeviceConfiguration() {
1775 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001776 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001777 deviceConfiguration = new DeviceConfiguration(this);
1778 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001779 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001780 deviceConfiguration.updateConfig();
1781 }
1782 }
1783
Charles Chanfbcb8812018-04-18 18:41:05 -07001784 private void createOrUpdateDefaultRoutingHandler() {
1785 if (defaultRoutingHandler == null) {
1786 log.info("Creating new DefaultRoutingHandler");
1787 defaultRoutingHandler = new DefaultRoutingHandler(this);
1788 } else {
1789 log.info("Updating DefaultRoutingHandler");
1790 defaultRoutingHandler.update(this);
1791 }
1792 }
1793
Pier Ventreb6a7f342016-11-26 21:05:22 -08001794 /**
1795 * Registers the given connect point with the NRS, this is necessary
1796 * to receive the NDP and ARP packets from the NRS.
1797 *
1798 * @param portToRegister connect point to register
1799 */
1800 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001801 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001802 portToRegister,
1803 neighbourHandler,
1804 appId
1805 );
1806 }
1807
Charles Chan72f556a2015-10-05 17:50:33 -07001808 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001809 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001810 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001811
Charles Chanb7f75ac2016-01-11 18:28:54 -08001812 /**
1813 * Constructs the internal network config listener.
1814 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001815 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001816 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001817 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001818 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001819 }
1820
Charles Chanb7f75ac2016-01-11 18:28:54 -08001821 /**
1822 * Reads network config and initializes related data structure accordingly.
1823 */
Charles Chan873661e2017-11-30 15:37:50 -08001824 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001825 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001826
1827 // Setting handling of network configuration events completable future
1828 // The completable future is needed because of the async behaviour of the configureNetwork,
1829 // listener registration and event arrival
1830 // Enables us to buffer the events and execute them when the configure network is done.
Ray Milkey521e4392018-11-16 15:15:14 -08001831 synchronized (networkConfigCompletionLock) {
1832 networkConfigCompletion = new CompletableFuture<>();
Andrea Campanella060cad82018-04-17 12:09:34 +02001833
Ray Milkey521e4392018-11-16 15:15:14 -08001834 // add a small delay to absorb multiple network config added notifications
1835 if (!programmingScheduled.get()) {
1836 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1837 programmingScheduled.set(true);
1838 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1839 }
1840
1841 createOrUpdateDeviceConfiguration();
1842
1843 arpHandler = new ArpHandler(srManager);
1844 icmpHandler = new IcmpHandler(srManager);
1845 ipHandler = new IpHandler(srManager);
1846 routingRulePopulator = new RoutingRulePopulator(srManager);
1847 createOrUpdateDefaultRoutingHandler();
1848
1849 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1850 groupHandlerMap, tunnelStore);
1851 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1852 flowObjectiveService,
1853 tunnelHandler, policyStore);
1854 networkConfigCompletion.complete(true);
Andrea Campanella060cad82018-04-17 12:09:34 +02001855 }
1856
Charles Chan72779502016-04-23 17:36:10 -07001857 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001858
Charles Chane7c61022015-10-07 14:21:45 -07001859 }
1860
Charles Chan72f556a2015-10-05 17:50:33 -07001861 @Override
1862 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001863 if (mainEventExecutor == null) {
1864 return;
1865 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001866 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan3f4aca62018-03-21 16:57:47 -07001867 switch (event.type()) {
1868 case CONFIG_ADDED:
1869 case CONFIG_UPDATED:
1870 case CONFIG_REMOVED:
Andrea Campanella060cad82018-04-17 12:09:34 +02001871 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
Charles Chan152dd942020-07-21 15:33:31 -07001872 log.debug("Process netcfg {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001873 mainEventExecutor.execute(new InternalEventHandler(event));
1874 } else {
Charles Chan152dd942020-07-21 15:33:31 -07001875 log.debug("Queue netcfg {}", event);
Charles Chan39b75522018-04-21 00:44:29 -07001876 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001877 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001878 break;
1879 default:
1880 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001881 }
1882 }
Saurav Das261c3002017-06-13 15:35:54 -07001883
Charles Chanc4a68c32018-01-03 16:26:32 -08001884 @Override
1885 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001886 if (event.type() == CONFIG_REGISTERED ||
1887 event.type() == CONFIG_UNREGISTERED) {
1888 log.debug("Ignore event {} due to type mismatch", event);
1889 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001890 }
Saurav Dase321cff2018-02-09 17:26:45 -08001891
1892 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1893 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
Charles Chana01d57c2019-07-19 16:25:38 -07001894 !event.configClass().equals(InterfaceConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001895 log.debug("Ignore event {} due to class mismatch", event);
1896 return false;
1897 }
1898
1899 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001900 }
1901
Saurav Das261c3002017-06-13 15:35:54 -07001902 private final class ConfigChange implements Runnable {
1903 @Override
1904 public void run() {
1905 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001906 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001907 for (Device device : deviceService.getDevices()) {
1908 processDeviceAdded(device);
1909 }
1910 defaultRoutingHandler.startPopulationProcess();
1911 }
1912 }
Charles Chan72f556a2015-10-05 17:50:33 -07001913 }
Charles Chanf4586112015-11-09 16:37:23 -08001914
Charles Chan3f4aca62018-03-21 16:57:47 -07001915 private class InternalLinkListener implements LinkListener {
1916 @Override
1917 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001918 if (mainEventExecutor == null) {
1919 return;
1920 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001921 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1922 event.type() == LinkEvent.Type.LINK_UPDATED ||
1923 event.type() == LinkEvent.Type.LINK_REMOVED) {
1924 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001925 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1926 mainEventExecutor.execute(new InternalEventHandler(event));
1927 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001928 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001929 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001930 }
1931 }
1932 }
1933
1934 private class InternalDeviceListener implements DeviceListener {
1935 @Override
1936 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001937 if (mainEventExecutor == null) {
1938 return;
1939 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001940 switch (event.type()) {
1941 case DEVICE_ADDED:
1942 case PORT_UPDATED:
1943 case PORT_ADDED:
1944 case DEVICE_UPDATED:
1945 case DEVICE_AVAILABILITY_CHANGED:
1946 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001947 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1948 mainEventExecutor.execute(new InternalEventHandler(event));
1949 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001950 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001951 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001952 break;
1953 default:
1954 }
1955 }
1956 }
1957
1958 private class InternalTopologyListener implements TopologyListener {
1959 @Override
1960 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001961 if (mainEventExecutor == null) {
1962 return;
1963 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001964 switch (event.type()) {
1965 case TOPOLOGY_CHANGED:
1966 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001967 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1968 mainEventExecutor.execute(new InternalEventHandler(event));
1969 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001970 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001971 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001972 break;
1973 default:
1974 }
1975 }
1976 }
1977
Charles Chanf4586112015-11-09 16:37:23 -08001978 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001979 @Override
1980 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001981 if (hostEventExecutor == null) {
1982 return;
1983 }
Charles Chanf4586112015-11-09 16:37:23 -08001984 switch (event.type()) {
1985 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001986 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001987 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001988 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001989 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001990 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08001991 break;
1992 default:
1993 log.warn("Unsupported host event type: {}", event.type());
1994 break;
1995 }
1996 }
1997 }
1998
Charles Chanc91c8782016-03-30 17:54:24 -07001999 private class InternalMcastListener implements McastListener {
2000 @Override
2001 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002002 if (mcastEventExecutor == null) {
2003 return;
2004 }
Charles Chanc91c8782016-03-30 17:54:24 -07002005 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07002006 case SOURCES_ADDED:
2007 case SOURCES_REMOVED:
2008 case SINKS_ADDED:
2009 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07002010 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02002011 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07002012 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07002013 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01002014 break;
Charles Chanc91c8782016-03-30 17:54:24 -07002015 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07002016 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07002017 break;
2018 }
2019 }
2020 }
Charles Chan41f5ec02016-06-13 18:54:31 -07002021
Charles Chandebfea32016-10-24 14:52:01 -07002022 private class InternalRouteEventListener implements RouteListener {
2023 @Override
2024 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002025 if (routeEventExecutor == null) {
2026 return;
2027 }
Charles Chandebfea32016-10-24 14:52:01 -07002028 switch (event.type()) {
2029 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07002030 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07002031 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07002032 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07002033 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07002034 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07002035 break;
Charles Chandebfea32016-10-24 14:52:01 -07002036 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07002037 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07002038 break;
2039 }
2040 }
2041 }
Saurav Das62ae6792017-05-15 15:34:25 -07002042
Charles Chanfbcb8812018-04-18 18:41:05 -07002043 private class InternalMastershipListener implements MastershipListener {
2044 @Override
2045 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002046 if (mainEventExecutor == null) {
2047 return;
2048 }
Charles Chanfbcb8812018-04-18 18:41:05 -07002049 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07002050 case MASTER_CHANGED:
2051 log.debug("Mastership event: {}/{}", event.subject(),
2052 event.roleInfo());
2053 mainEventExecutor.execute(new InternalEventHandler(event));
2054 break;
2055 case BACKUPS_CHANGED:
2056 case SUSPENDED:
2057 default:
2058 log.debug("Mastership event type {} not handled", event.type());
2059 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07002060 }
2061 }
2062 }
2063
Saurav Das00e553b2018-04-21 17:19:48 -07002064 class InternalClusterListener implements ClusterEventListener {
2065 private Instant lastClusterEvent = Instant.EPOCH;
2066
2067 long timeSinceLastClusterEvent() {
2068 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
2069 }
2070
2071 @Override
2072 public void event(ClusterEvent event) {
2073 switch (event.type()) {
2074 case INSTANCE_ACTIVATED:
2075 case INSTANCE_ADDED:
2076 case INSTANCE_READY:
2077 log.debug("Cluster event {} ignored", event.type());
2078 break;
2079 case INSTANCE_DEACTIVATED:
2080 case INSTANCE_REMOVED:
2081 log.info("** Cluster event {}", event.type());
2082 lastClusterEvent = Instant.now();
2083 break;
2084 default:
2085 break;
2086 }
2087
2088 }
2089
2090 }
2091
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002092 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
2093 try {
2094 Set<Interface> intfs = conf.getInterfaces();
2095 Set<Interface> prevIntfs = prevConf.getInterfaces();
2096
2097 // Now we only handle one interface config at each port.
2098 if (intfs.size() != 1 || prevIntfs.size() != 1) {
2099 log.warn("Interface update aborted - one at a time is allowed, " +
2100 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
2101 return;
2102 }
2103
Andrea Campanella060cad82018-04-17 12:09:34 +02002104 //The system is in an incoherent state, abort
2105 if (defaultRoutingHandler == null) {
2106 log.warn("Interface update aborted, defaultRoutingHandler is null");
2107 return;
2108 }
2109
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002110 Interface intf = intfs.stream().findFirst().get();
2111 Interface prevIntf = prevIntfs.stream().findFirst().get();
2112
2113 DeviceId deviceId = intf.connectPoint().deviceId();
2114 PortNumber portNum = intf.connectPoint().port();
pierventrea3989be2021-01-08 16:43:17 +01002115 // We need to do nexthop update al least one time for each
2116 // interface config change. There is no difference when it is done;
2117 boolean updateNexthop = false;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002118
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002119 removeSubnetConfig(prevIntf.connectPoint(),
2120 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
2121 new HashSet<>(intf.ipAddressesList())));
2122
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002123 if (!prevIntf.vlanNative().equals(VlanId.NONE)
2124 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
2125 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
2126 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
2127 // Update filtering objective and L2IG group bucket
2128 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
2129 } else {
pierventrea3989be2021-01-08 16:43:17 +01002130 // RemoveVlanNative - affected scenarios:
2131 // (T,N)->U; (T*,N)->U; (T,N)->(T,N); (T,N)->T
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002132 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
pierventrea3989be2021-01-08 16:43:17 +01002133 // Update the nexthops of the indirect routes
2134 updateNexthop = true;
2135 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002136 }
2137 }
2138
2139 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
2140 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2141 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2142 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002143 // Update filtering objective and L2IG group bucket - affected scenarios:
2144 // U->(T*,N); U->T*
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002145 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
pierventrea3989be2021-01-08 16:43:17 +01002146 if (!updateNexthop) {
2147 updateNexthop = true;
2148 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2149 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002150 } else {
pierventrea3989be2021-01-08 16:43:17 +01002151 // RemoveVlanUntagged - affected scenarios:
2152 // U->U; U->(T,N); U->T
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002153 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
pierventrea3989be2021-01-08 16:43:17 +01002154 if (!updateNexthop) {
2155 updateNexthop = true;
2156 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2157 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002158 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002159 }
2160
2161 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002162 // RemoveVlanTagged - affected scenarios:
2163 // T->U; T->T; (T,N*)->U; (T,N)->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002164 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2165 .filter(i -> !intf.vlanUntagged().equals(i))
2166 .filter(i -> !intf.vlanNative().equals(i))
2167 .forEach(vlanId -> updateVlanConfigInternal(
2168 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002169 }
2170
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002171 if (!intf.vlanNative().equals(VlanId.NONE)
2172 && !prevIntf.vlanNative().equals(intf.vlanNative())
2173 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2174 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2175 // Update filtering objective and L2IG group bucket
2176 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2177 } else {
pierventrea3989be2021-01-08 16:43:17 +01002178 // AddVlanNative - affected scenarios
2179 // U->(T,N); U->(T*,N); T->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002180 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
pierventrea3989be2021-01-08 16:43:17 +01002181 if (!updateNexthop) {
2182 updateNexthop = true;
2183 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2184 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002185 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002186 }
2187
2188 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002189 // AddVlanTagged - affected scenarios
2190 // U->T; U->(T,N*); T->T; (T,N)->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002191 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2192 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2193 .filter(i -> !prevIntf.vlanNative().equals(i))
2194 .forEach(vlanId -> updateVlanConfigInternal(
2195 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002196 );
pierventrea3989be2021-01-08 16:43:17 +01002197
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002198 }
2199
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002200 if (!intf.vlanUntagged().equals(VlanId.NONE)
2201 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2202 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2203 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002204 // Update filtering objective and L2IG group bucket - affected scenarios
2205 // (T*,N)->U; T*->U
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002206 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
pierventrea3989be2021-01-08 16:43:17 +01002207 if (!updateNexthop) {
2208 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2209 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002210 } else {
pierventrea3989be2021-01-08 16:43:17 +01002211 // AddVlanUntagged - affected scenarios
2212 // U->U; (T,N)->U; T->U
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002213 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
pierventrea3989be2021-01-08 16:43:17 +01002214 if (!updateNexthop) {
2215 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2216 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002217 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002218 }
2219 addSubnetConfig(prevIntf.connectPoint(),
2220 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2221 new HashSet<>(prevIntf.ipAddressesList())));
2222 } catch (ConfigException e) {
2223 log.error("Error in configuration");
2224 }
2225 }
2226
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002227 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2228 VlanId vlanId, boolean pushVlan) {
2229 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2230 if (grpHandler == null) {
2231 log.warn("Failed to retrieve group handler for device {}", deviceId);
2232 return;
2233 }
2234
2235 // Update filtering objective for a single port
2236 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2237 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2238
2239 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2240 // Update L2IG bucket of the port
2241 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2242 } else {
2243 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2244 }
2245 }
2246
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002247 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2248 VlanId vlanId, boolean pushVlan, boolean install) {
2249 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2250 if (grpHandler == null) {
2251 log.warn("Failed to retrieve group handler for device {}", deviceId);
2252 return;
2253 }
2254
2255 // Update filtering objective for a single port
2256 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2257
2258 // Update filtering objective for multicast ingress port
2259 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2260
2261 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2262
2263 if (nextId != -1 && !install) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002264 // Remove L2 Bridging rule and L3 Unicast rule to the host
pierventrea3989be2021-01-08 16:43:17 +01002265 ScheduledFuture<?> future = hostEventExecutor.schedule(
2266 () -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install),
2267 0, TimeUnit.SECONDS);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002268 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2269 // only if there is no port configured on that VLAN ID
2270 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2271 // Remove broadcast forwarding rule for the VLAN
2272 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2273 // Remove L2FG for VLAN
2274 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2275 } else {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002276 // Remove a single port from L2FG
2277 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002278 }
pierventrea3989be2021-01-08 16:43:17 +01002279 // Before moving forward we have to be sure that processIntfVlanUpdatedEvent completed;
2280 try {
2281 future.get();
2282 } catch (InterruptedException | ExecutionException e) {
2283 log.warn("Exception caught when executing updateVlanConfigInternal future");
2284 }
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002285 // Remove L2IG of the port
2286 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002287 } else if (install) {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002288 // Create L2IG of the port
2289 grpHandler.createPortNextObjective(deviceId, portNum, vlanId, pushVlan);
2290 // Create L2 Bridging rule and L3 Unicast rule to the host
2291 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2292 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002293 if (nextId != -1) {
2294 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002295 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002296 } else {
2297 // Create L2FG for VLAN
2298 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2299 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2300 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002301 } else {
2302 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2303 }
2304 }
2305
2306 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2307 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2308 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2309
2310 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2311 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2312 .filter(intf -> !intf.connectPoint().equals(cp))
2313 .flatMap(intf -> intf.ipAddressesList().stream())
2314 .collect(Collectors.toSet());
2315 // 1. Partial subnet population
2316 // Remove routing rules for removed subnet from previous configuration,
2317 // which does not also exist in other interfaces in the same device
2318 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2319 .map(InterfaceIpAddress::subnetAddress)
2320 .collect(Collectors.toSet());
2321
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002322 Set<IpPrefix> subnetsToBeRevoked = ipPrefixSet.stream()
2323 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2324 .collect(Collectors.toSet());
2325
2326 // Check if any of the subnets to be revoked is configured in the pairDevice.
2327 // If any, repopulate the subnet with pairDevice connectPoint instead of revoking.
2328 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2329 if (pairDevice.isPresent()) {
2330 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2331
2332 Set<IpPrefix> subnetsExistingInPairDevice = subnetsToBeRevoked.stream()
2333 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2334 .collect(Collectors.toSet());
2335
2336 // Update the subnets existing in pair device with pair device connect point.
2337 if (!subnetsExistingInPairDevice.isEmpty()) {
2338 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2339 ConnectPoint pairDeviceCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2340 log.debug("Updating the subnets: {} with pairDevice connectPoint as it exists in the Pair device: {}",
2341 subnetsExistingInPairDevice, pairDeviceCp);
2342 defaultRoutingHandler.populateSubnet(Collections.singleton(pairDeviceCp), subnetsExistingInPairDevice);
2343 }
2344
2345 // Remove only the subnets that are not configured in the pairDevice.
2346 subnetsToBeRevoked = Sets.difference(subnetsToBeRevoked, subnetsExistingInPairDevice);
2347 }
2348
2349 if (!subnetsToBeRevoked.isEmpty()) {
2350 log.debug("Removing subnets for connectPoint: {}, subnets: {}", cp, subnetsToBeRevoked);
2351 defaultRoutingHandler.revokeSubnet(subnetsToBeRevoked);
2352 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002353
2354 // 2. Interface IP punts
2355 // Remove IP punts for old Intf address
2356 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2357 .map(InterfaceIpAddress::ipAddress)
2358 .collect(Collectors.toSet());
2359 ipAddressSet.stream()
2360 .map(InterfaceIpAddress::ipAddress)
2361 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2362 .forEach(interfaceIpAddress ->
2363 routingRulePopulator.revokeSingleIpPunts(
2364 cp.deviceId(), interfaceIpAddress));
2365
2366 // 3. Host unicast routing rule
2367 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002368 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002369 }
2370
2371 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2372 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2373 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2374
2375 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2376 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2377 .filter(intf -> !intf.connectPoint().equals(cp))
2378 .flatMap(intf -> intf.ipAddressesList().stream())
2379 .collect(Collectors.toSet());
2380 // 1. Partial subnet population
2381 // Add routing rules for newly added subnet, which does not also exist in
2382 // other interfaces in the same device
2383 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2384 .map(InterfaceIpAddress::subnetAddress)
2385 .collect(Collectors.toSet());
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002386 Set<IpPrefix> subnetsToBePopulated = ipPrefixSet.stream()
2387 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2388 .collect(Collectors.toSet());
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002389
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002390 if (!subnetsToBePopulated.isEmpty()) {
2391 log.debug("Adding subnets for connectPoint: {}, subnets: {}", cp, subnetsToBePopulated);
2392
2393 // check if pair-device has the same subnet configured?
2394 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2395 if (pairDevice.isPresent()) {
2396 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2397
2398 Set<IpPrefix> subnetsToBePopulatedAsDualHomed = subnetsToBePopulated.stream()
2399 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2400 .collect(Collectors.toSet());
2401 Set<IpPrefix> subnetsToBePopulatedAsSingleHomed = Sets.difference(subnetsToBePopulated,
2402 subnetsToBePopulatedAsDualHomed);
2403
2404 if (!subnetsToBePopulatedAsSingleHomed.isEmpty()) {
2405 defaultRoutingHandler.populateSubnet(
2406 Collections.singleton(cp),
2407 subnetsToBePopulatedAsSingleHomed);
2408 }
2409
2410 if (!subnetsToBePopulatedAsDualHomed.isEmpty()) {
2411 Set<ConnectPoint> cpts = new HashSet<>();
2412 cpts.add(cp);
2413 // As Subnets is DualHomed adding the pairDevice also as ConnectPoint.
2414 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2415 ConnectPoint pairCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2416 cpts.add(pairCp);
2417
2418 log.debug("Adding DualHomed subnets for connectPoint: {} and its pair device: {}, subnets: {}",
2419 cp, pairCp, subnetsToBePopulatedAsDualHomed);
2420
2421 // populating the subnets as DualHomed
2422 defaultRoutingHandler.populateSubnet(
2423 cpts,
2424 subnetsToBePopulated);
2425
2426 // revoking the subnets populated in the device as it is now Dualhomed.
2427 defaultRoutingHandler.revokeSubnet(Collections.singleton(cp.deviceId()),
2428 subnetsToBePopulatedAsDualHomed);
2429 }
2430 } else {
2431 defaultRoutingHandler.populateSubnet(
2432 Collections.singleton(cp),
2433 subnetsToBePopulated);
2434 }
2435 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002436
2437 // 2. Interface IP punts
2438 // Add IP punts for new Intf address
2439 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2440 .map(InterfaceIpAddress::ipAddress)
2441 .collect(Collectors.toSet());
2442 ipAddressSet.stream()
2443 .map(InterfaceIpAddress::ipAddress)
2444 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2445 .forEach(interfaceIpAddress ->
2446 routingRulePopulator.populateSingleIpPunts(
2447 cp.deviceId(), interfaceIpAddress));
2448
2449 // 3. Host unicast routing rule
2450 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002451 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002452 }
sangho80f11cb2015-04-01 13:05:26 -07002453}