blob: c42773f1eb2f0d6cd9355cede5302553c4908e99 [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;
pierventrec80a5052021-05-20 12:56:38 +020020import com.google.common.collect.Lists;
Jonathan Hart61e24e12017-11-30 18:23:42 -080021import com.google.common.collect.Maps;
22import com.google.common.collect.Multimap;
Charles Chanf0ae41e2017-08-23 13:55:39 -070023import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070024import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080025import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070026import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080027import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070028import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070029import org.onlab.packet.IpPrefix;
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +000030import org.onlab.packet.MacAddress;
Carmelo Cascone61004262020-01-16 13:36:02 -080031import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070032import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080033import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070034import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070035import org.onosproject.cluster.ClusterEvent;
36import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010037import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070038import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020039import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070040import org.onosproject.core.ApplicationId;
41import org.onosproject.core.CoreService;
42import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070043import org.onosproject.mastership.MastershipEvent;
44import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070045import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070046import org.onosproject.mcast.api.McastEvent;
47import org.onosproject.mcast.api.McastListener;
48import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080049import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070050import org.onosproject.net.Device;
51import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070052import org.onosproject.net.Host;
53import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070054import org.onosproject.net.Link;
55import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080056import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070057import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070058import org.onosproject.net.config.ConfigFactory;
59import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070060import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070061import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070062import org.onosproject.net.config.basics.InterfaceConfig;
63import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070064import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080065import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070066import org.onosproject.net.device.DeviceEvent;
67import org.onosproject.net.device.DeviceListener;
68import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080069import org.onosproject.net.flow.TrafficSelector;
70import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070071import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070072import org.onosproject.net.flowobjective.NextObjective;
Charles Chanf4586112015-11-09 16:37:23 -080073import org.onosproject.net.host.HostEvent;
74import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070075import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080076import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070077import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020078import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070079import org.onosproject.net.intf.Interface;
80import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080081import org.onosproject.net.link.LinkEvent;
82import org.onosproject.net.link.LinkListener;
83import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070084import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080085import org.onosproject.net.packet.InboundPacket;
86import org.onosproject.net.packet.PacketContext;
87import org.onosproject.net.packet.PacketProcessor;
88import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010089import org.onosproject.net.topology.TopologyEvent;
90import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070091import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070092import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070093import org.onosproject.routeservice.RouteEvent;
94import org.onosproject.routeservice.RouteListener;
95import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070096import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
Pier Ventre6b19e482016-11-07 16:21:04 -080097import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -070098import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanc91c8782016-03-30 17:54:24 -070099import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700100import org.onosproject.segmentrouting.grouphandler.DestinationSet;
101import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Harshada Chaundkar9204f312019-07-02 16:01:24 +0000102import org.onosproject.segmentrouting.mcast.McastFilteringObjStoreKey;
Pier Luigi69f774d2018-02-28 12:10:50 +0100103import org.onosproject.segmentrouting.mcast.McastHandler;
104import org.onosproject.segmentrouting.mcast.McastRole;
Piere99511d2018-04-19 16:47:06 +0200105import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700106import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chan12a8a842020-02-14 13:23:57 -0800107import org.onosproject.segmentrouting.phasedrecovery.api.PhasedRecoveryService;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700108import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700109import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700111import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800112import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700113import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700114import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800115import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Saurav Das261c3002017-06-13 15:35:54 -0700116import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Carmelo Cascone61004262020-01-16 13:36:02 -0800117import org.onosproject.segmentrouting.storekey.MacVlanNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700118import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800119import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700120import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700121import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700122import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700123import org.onosproject.store.service.EventuallyConsistentMap;
124import org.onosproject.store.service.EventuallyConsistentMapBuilder;
125import org.onosproject.store.service.StorageService;
126import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800127import org.osgi.service.component.ComponentContext;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700128import org.osgi.service.component.annotations.Activate;
129import org.osgi.service.component.annotations.Component;
130import org.osgi.service.component.annotations.Deactivate;
131import org.osgi.service.component.annotations.Modified;
132import org.osgi.service.component.annotations.Reference;
133import org.osgi.service.component.annotations.ReferenceCardinality;
Charles Chanb4f9cd12019-02-27 11:46:32 -0800134import org.osgi.service.component.annotations.ReferencePolicy;
sangho80f11cb2015-04-01 13:05:26 -0700135import org.slf4j.Logger;
136import org.slf4j.LoggerFactory;
137
Saurav Das00e553b2018-04-21 17:19:48 -0700138import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700139import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800140import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800141import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800142import java.util.HashSet;
143import java.util.List;
144import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800145import java.util.Optional;
146import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200147import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800148import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200149import java.util.concurrent.CopyOnWriteArrayList;
pierventrea3989be2021-01-08 16:43:17 +0100150import java.util.concurrent.ExecutionException;
Charles Chan77cdde42018-05-08 21:35:50 -0700151import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800152import java.util.concurrent.Executors;
153import java.util.concurrent.ScheduledExecutorService;
pierventrea3989be2021-01-08 16:43:17 +0100154import java.util.concurrent.ScheduledFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800155import java.util.concurrent.TimeUnit;
156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700158
Charles Chand6d25332016-02-26 22:19:52 -0800159import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800160import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700161import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
163import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700164import static org.onosproject.segmentrouting.OsgiPropertyConstants.ACTIVE_PROBING_DEFAULT;
165import static org.onosproject.segmentrouting.OsgiPropertyConstants.DEFAULT_INTERNAL_VLAN_DEFAULT;
166import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ACTIVE_PROBING;
167import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_DEFAULT_INTERNAL_VLAN;
168import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_PW_TRANSPORT_VLAN;
169import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_RESPOND_TO_UNKNOWN_HOSTS;
170import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_DOUBLE_TAGGED_HOSTS;
psneha86e60d32019-03-26 06:31:41 -0400171import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_SIMPLIFICATION;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700172import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SINGLE_HOMED_DOWN;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700173import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SYMMETRIC_PROBING;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700174import static org.onosproject.segmentrouting.OsgiPropertyConstants.PW_TRANSPORT_VLAN_DEFAULT;
175import static org.onosproject.segmentrouting.OsgiPropertyConstants.RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
176import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
psneha86e60d32019-03-26 06:31:41 -0400177import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_SIMPLIFICATION_DEFAULT;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700178import static org.onosproject.segmentrouting.OsgiPropertyConstants.SINGLE_HOMED_DOWN_DEFAULT;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700179import static org.onosproject.segmentrouting.OsgiPropertyConstants.SYMMETRIC_PROBING_DEFAULT;
Charles Chand6d25332016-02-26 22:19:52 -0800180
Charles Chanb7f75ac2016-01-11 18:28:54 -0800181/**
182 * Segment routing manager.
183 */
Ray Milkey05edbfc2018-10-23 14:23:16 -0700184@Component(
185 immediate = true,
186 service = SegmentRoutingService.class,
187 property = {
188 PROP_ACTIVE_PROBING + ":Boolean=" + ACTIVE_PROBING_DEFAULT,
189 PROP_SINGLE_HOMED_DOWN + ":Boolean=" + SINGLE_HOMED_DOWN_DEFAULT,
190 PROP_RESPOND_TO_UNKNOWN_HOSTS + ":Boolean=" + RESPOND_TO_UNKNOWN_HOSTS_DEFAULT,
191 PROP_ROUTE_DOUBLE_TAGGED_HOSTS + ":Boolean=" + ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT,
192 PROP_DEFAULT_INTERNAL_VLAN + ":Integer=" + DEFAULT_INTERNAL_VLAN_DEFAULT,
193 PROP_PW_TRANSPORT_VLAN + ":Integer=" + PW_TRANSPORT_VLAN_DEFAULT,
psneha86e60d32019-03-26 06:31:41 -0400194 PROP_SYMMETRIC_PROBING + ":Boolean=" + SYMMETRIC_PROBING_DEFAULT,
195 PROP_ROUTE_SIMPLIFICATION + ":Boolean=" + ROUTE_SIMPLIFICATION_DEFAULT
Ray Milkey05edbfc2018-10-23 14:23:16 -0700196 }
197)
sangho27462c62015-05-14 00:39:53 -0700198public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700199
Charles Chan46fdfaf2016-11-09 20:51:44 -0800200 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700201 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700202
Ray Milkey2bd24a92018-08-17 14:54:17 -0700203 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700204 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700205
Ray Milkey2bd24a92018-08-17 14:54:17 -0700206 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chancf789822019-03-22 10:04:27 -0700207 public NeighbourResolutionService neighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800208
Ray Milkey2bd24a92018-08-17 14:54:17 -0700209 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100210 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700211
Ray Milkey2bd24a92018-08-17 14:54:17 -0700212 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700213 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700214
Ray Milkey2bd24a92018-08-17 14:54:17 -0700215 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700216 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700217
Ray Milkey2bd24a92018-08-17 14:54:17 -0700218 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700219 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800220
Ray Milkey2bd24a92018-08-17 14:54:17 -0700221 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100222 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700223
Ray Milkey2bd24a92018-08-17 14:54:17 -0700224 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800225 DeviceAdminService deviceAdminService;
226
Ray Milkey2bd24a92018-08-17 14:54:17 -0700227 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800228 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700229
Ray Milkey2bd24a92018-08-17 14:54:17 -0700230 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100231 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700232
Ray Milkey2bd24a92018-08-17 14:54:17 -0700233 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800234 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700235
Ray Milkey2bd24a92018-08-17 14:54:17 -0700236 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800237 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700238
Ray Milkey2bd24a92018-08-17 14:54:17 -0700239 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100240 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700241
Ray Milkey2bd24a92018-08-17 14:54:17 -0700242 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan83163812018-01-09 13:45:07 -0800243 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700244
Ray Milkey2bd24a92018-08-17 14:54:17 -0700245 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan19b70032019-04-17 14:20:26 -0700246 public RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800247
Ray Milkey2bd24a92018-08-17 14:54:17 -0700248 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800249 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800250
Ray Milkey2bd24a92018-08-17 14:54:17 -0700251 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800252 public InterfaceService interfaceService;
253
Ray Milkey2bd24a92018-08-17 14:54:17 -0700254 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi580fd8a2018-01-16 10:47:50 +0100255 public ClusterService clusterService;
256
Ray Milkey2bd24a92018-08-17 14:54:17 -0700257 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pierdb27b8d2018-04-17 16:29:56 +0200258 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100259
Ray Milkey2bd24a92018-08-17 14:54:17 -0700260 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700261 public LeadershipService leadershipService;
262
Charles Chanb4f9cd12019-02-27 11:46:32 -0800263 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
Charles Chanb4f9cd12019-02-27 11:46:32 -0800264 policy = ReferencePolicy.DYNAMIC)
Carmelo Cascone61004262020-01-16 13:36:02 -0800265 public volatile XconnectService xconnectService;
Charles Chan8d316332018-06-19 20:31:57 -0700266
Charles Chan12a8a842020-02-14 13:23:57 -0800267 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
268 policy = ReferencePolicy.DYNAMIC)
269 volatile PhasedRecoveryService phasedRecoveryService;
270
Ray Milkey05edbfc2018-10-23 14:23:16 -0700271 /** Enable active probing to discover dual-homed hosts. */
272 boolean activeProbing = ACTIVE_PROBING_DEFAULT;
Charles Chan873661e2017-11-30 15:37:50 -0800273
Ray Milkeye96d0de2018-11-02 17:12:21 -0700274 /** Enable only send probe on the same port number of the pair device. */
275 boolean symmetricProbing = SYMMETRIC_PROBING_DEFAULT;
Mayank Tiwarif7942402018-10-29 18:27:35 -0400276
Ray Milkey05edbfc2018-10-23 14:23:16 -0700277 /** Enable administratively taking down single-homed hosts. */
278 boolean singleHomedDown = SINGLE_HOMED_DOWN_DEFAULT;
Saurav Dasec683dc2018-04-27 18:42:30 -0700279
Ray Milkey05edbfc2018-10-23 14:23:16 -0700280 /** Enable this to respond to ARP/NDP requests from unknown hosts. */
281 boolean respondToUnknownHosts = RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700282
Ray Milkey05edbfc2018-10-23 14:23:16 -0700283 /** Program flows and groups to pop and route double tagged hosts. */
284 boolean routeDoubleTaggedHosts = ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
Charles Chan4eb73bb2018-07-19 14:55:31 -0700285
Ray Milkey05edbfc2018-10-23 14:23:16 -0700286 /** internal vlan assigned by default to unconfigured ports. */
287 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700288
Ray Milkey05edbfc2018-10-23 14:23:16 -0700289 /** vlan used for transport of pseudowires between switches. */
290 private int pwTransportVlan = PW_TRANSPORT_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700291
psneha86e60d32019-03-26 06:31:41 -0400292 /** Enabling route simplification. */
293 boolean routeSimplification = ROUTE_SIMPLIFICATION_DEFAULT;
294
Charles Chandebfea32016-10-24 14:52:01 -0700295 ArpHandler arpHandler = null;
296 IcmpHandler icmpHandler = null;
297 IpHandler ipHandler = null;
298 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700299 ApplicationId appId;
300 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700301
Charles Chandebfea32016-10-24 14:52:01 -0700302 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700303 private TunnelHandler tunnelHandler = null;
304 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700305 private InternalPacketProcessor processor = null;
306 private InternalLinkListener linkListener = null;
307 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700308 private AppConfigHandler appCfgHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800309 McastHandler mcastHandler = null;
310 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800311 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800312 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800313 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800314 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100315 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800316 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700317 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
318 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700319 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100320 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700321 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700322 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200323 //Completable future for network configuration process to buffer config events handling during activation
324 private CompletableFuture<Boolean> networkConfigCompletion = null;
Ray Milkey521e4392018-11-16 15:15:14 -0800325 private final Object networkConfigCompletionLock = new Object();
Charles Chan39b75522018-04-21 00:44:29 -0700326 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700327
Charles Chan52003922018-04-05 16:31:15 -0700328 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700329 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700330
Charles Chanfbcb8812018-04-18 18:41:05 -0700331 // Handles host, route and mcast events respectively
332 private ScheduledExecutorService hostEventExecutor;
333 private ScheduledExecutorService routeEventExecutor;
334 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700335 private ExecutorService packetExecutor;
Charles Chana7601c92019-01-23 15:03:17 -0800336 ExecutorService neighborExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700337
338 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800339 /**
Saurav Das261c3002017-06-13 15:35:54 -0700340 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700341 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800342 */
Charles Chan873661e2017-11-30 15:37:50 -0800343 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700344 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800345 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700346 * Per device next objective ID store with (device id + vlanid) as key.
347 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800348 */
Charles Chan873661e2017-11-30 15:37:50 -0800349 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800350 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800351 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700352 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000353 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800354 */
Charles Chan873661e2017-11-30 15:37:50 -0800355 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800356 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800357
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700358 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000359 * Per device next objective ID store with (device id + MAC address + vlan) as key.
360 * Used to keep track of L3 unicast group for indirect hosts.
361 */
362 private EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer>
363 macVlanNextObjStore = null;
364
Saurav Das2d94d312015-11-24 23:21:05 -0800365 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
366 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700367
Saurav Das261c3002017-06-13 15:35:54 -0700368 private AtomicBoolean programmingScheduled = new AtomicBoolean();
369
Charles Chanc91c8782016-03-30 17:54:24 -0700370 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700371 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
372 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700373 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700374 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800375 public SegmentRoutingDeviceConfig createConfig() {
376 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700377 }
378 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800379
Charles Chanc91c8782016-03-30 17:54:24 -0700380 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700381 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
382 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700383 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800384 @Override
385 public SegmentRoutingAppConfig createConfig() {
386 return new SegmentRoutingAppConfig();
387 }
388 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800389
Charles Chanc91c8782016-03-30 17:54:24 -0700390 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700391 new ConfigFactory<ApplicationId, McastConfig>(
392 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700393 McastConfig.class, "multicast") {
394 @Override
395 public McastConfig createConfig() {
396 return new McastConfig();
397 }
398 };
399
Charles Chan1963f4f2016-02-18 14:22:42 -0800400 /**
401 * Segment Routing App ID.
402 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800403 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das7c305372015-10-28 12:39:42 -0700404
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700405 /**
406 * Minumum and maximum value of dummy VLAN ID to be allocated.
407 */
408 public static final int MIN_DUMMY_VLAN_ID = 2;
409 public static final int MAX_DUMMY_VLAN_ID = 4093;
410
Charles Chana7601c92019-01-23 15:03:17 -0800411 private static final int DEFAULT_POOL_SIZE = 32;
412
Saurav Dasec683dc2018-04-27 18:42:30 -0700413 Instant lastEdgePortEvent = Instant.EPOCH;
414
sangho80f11cb2015-04-01 13:05:26 -0700415 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800416 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800417 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700418
Charles Chana7601c92019-01-23 15:03:17 -0800419 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(
420 groupedThreads("onos/sr", "event-main-%d", log));
421 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(
422 groupedThreads("onos/sr", "event-host-%d", log));
423 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(
424 groupedThreads("onos/sr", "event-route-%d", log));
425 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(
426 groupedThreads("onos/sr", "event-mcast-%d", log));
427 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("onos/sr", "packet-%d", log));
428 neighborExecutor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE,
429 groupedThreads("onos/sr", "neighbor-%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700430
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700431 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700432 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700433 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700434 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700435 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700436 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700437 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700438 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700439 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700440
Charles Chan10b0fb72017-02-02 16:20:42 -0800441 log.debug("Creating EC map vlannextobjectivestore");
442 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
443 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
444 vlanNextObjStore = vlanNextObjMapBuilder
445 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700446 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700447 .withTimestampProvider((k, v) -> new WallClockTimestamp())
448 .build();
449
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000450 log.debug("Creating EC map macvlannextobjectivestore");
451 EventuallyConsistentMapBuilder<MacVlanNextObjectiveStoreKey, Integer>
452 macVlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
453 macVlanNextObjStore = macVlanNextObjMapBuilder
454 .withName("macvlannextobjectivestore")
455 .withSerializer(createSerializer())
456 .withTimestampProvider((k, v) -> new WallClockTimestamp())
457 .build();
458
Saurav Das2d94d312015-11-24 23:21:05 -0800459 log.debug("Creating EC map subnetnextobjectivestore");
460 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
461 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
462 portNextObjStore = portNextObjMapBuilder
463 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700464 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800465 .withTimestampProvider((k, v) -> new WallClockTimestamp())
466 .build();
467
sangho4a5c42a2015-05-20 22:16:38 -0700468 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
469 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700470 tunnelStore = tunnelMapBuilder
471 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700472 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700473 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700474 .build();
475
476 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
477 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700478 policyStore = policyMapBuilder
479 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700480 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700481 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700482 .build();
483
Charles Chan97979802020-02-26 15:04:44 -0800484 processor = new InternalPacketProcessor();
485 linkListener = new InternalLinkListener();
486 deviceListener = new InternalDeviceListener();
487 appCfgHandler = new AppConfigHandler(this);
488 mcastHandler = new McastHandler(this);
489 hostHandler = new HostHandler(this);
490 linkHandler = new LinkHandler(this);
491 routeHandler = new RouteHandler(this);
492 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
493 l2TunnelHandler = new DefaultL2TunnelHandler(this);
494 topologyHandler = new TopologyHandler(this);
495
Pier Luigib9632ba2017-01-12 18:14:58 -0800496 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700497 "requestInterceptsEnabled", "false", false);
Charles Chanc1909e12017-08-08 15:13:37 -0700498 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700499 "requestInterceptsEnabled", "false", false);
Charles Chan9597f8d2017-07-24 15:56:10 -0700500 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700501 "arpEnabled", "false", false);
Pier Luigi0ebeb312017-02-02 22:31:34 -0800502 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700503 "greedyLearningIpv6", "true", false);
Charles Chancf8ea472017-02-28 15:15:17 -0800504 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700505 "forceUnprovision", "true", false);
Charles Chanc7b73c72017-08-10 16:57:28 -0700506 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan0fa51db2019-04-10 17:12:20 -0700507 "distributed", "true", false);
Charles Chan804772f2017-08-14 11:42:11 -0700508 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700509 "multihomingEnabled", "true", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800510 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700511 "staleLinkAge", "15000", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800512 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700513 "allowDuplicateIps", "false", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800514 // For P4 switches
515 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700516 "fallbackFlowPollFrequency", "4", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800517 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700518 "fallbackGroupPollFrequency", "3", false);
Charles Chan873661e2017-11-30 15:37:50 -0800519 compCfgService.registerProperties(getClass());
520 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700521
Charles Chand6d25332016-02-26 22:19:52 -0800522 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700523 cfgService.registerConfigFactory(deviceConfigFactory);
524 cfgService.registerConfigFactory(appConfigFactory);
525 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800526 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200527
Charles Chan6961f222018-01-04 14:26:07 -0800528 cfgListener.configureNetwork();
529
Charles Chan82ab1932016-01-30 23:22:37 -0800530 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700531 packetService.addProcessor(processor, PacketProcessor.director(2));
532 linkService.addListener(linkListener);
533 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700534 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700535 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100536 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700537 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700538 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700539
Charles Chanc12c3d02018-03-09 15:53:44 -0800540 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800541 l2TunnelHandler.init();
542
pierventrec80a5052021-05-20 12:56:38 +0200543 drainEvents();
Andrea Campanella060cad82018-04-17 12:09:34 +0200544
sangho80f11cb2015-04-01 13:05:26 -0700545 log.info("Started");
546 }
547
pierventrec80a5052021-05-20 12:56:38 +0200548 // Drain buffered events
549 private void drainEvents() {
550 synchronized (networkConfigCompletionLock) {
551 final List<Event> processedEvents = Lists.newArrayList();
552 if (networkConfigCompletion != null) {
553 networkConfigCompletion.whenComplete((value, ex) -> {
554 //setting to null for easier fall through
555 networkConfigCompletion = null;
556 //process all queued events
557 queuedEvents.forEach(event -> {
558 mainEventExecutor.execute(new InternalEventHandler(event));
559 processedEvents.add(event);
560 });
561 // Removes all
562 queuedEvents.removeAll(processedEvents);
563 processedEvents.clear();
564 });
565 }
566 }
567 }
568
Saurav Dase6c448a2018-01-18 12:07:33 -0800569 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700570 return new KryoNamespace.Builder()
571 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700572 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800573 VlanNextObjectiveStoreKey.class,
574 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700575 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800576 NextNeighbors.class,
577 Tunnel.class,
578 DefaultTunnel.class,
579 Policy.class,
580 TunnelPolicy.class,
581 Policy.Type.class,
582 PortNextObjectiveStoreKey.class,
583 XConnectStoreKey.class,
584 L2Tunnel.class,
585 L2TunnelPolicy.class,
586 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700587 DefaultL2TunnelPolicy.class,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000588 MacVlanNextObjectiveStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700589 );
590 }
591
sangho80f11cb2015-04-01 13:05:26 -0700592 @Deactivate
593 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700594 mainEventExecutor.shutdown();
595 hostEventExecutor.shutdown();
596 routeEventExecutor.shutdown();
597 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700598 packetExecutor.shutdown();
Charles Chana7601c92019-01-23 15:03:17 -0800599 neighborExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700600
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700601 mainEventExecutor = null;
602 hostEventExecutor = null;
603 routeEventExecutor = null;
604 mcastEventExecutor = null;
605 packetExecutor = null;
Charles Chana7601c92019-01-23 15:03:17 -0800606 neighborExecutor = null;
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700607
Danny Chang44a7b952020-09-08 15:27:04 -0700608 cancelPackets();
609
Charles Chan72f556a2015-10-05 17:50:33 -0700610 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700611 cfgService.unregisterConfigFactory(deviceConfigFactory);
612 cfgService.unregisterConfigFactory(appConfigFactory);
613 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800614 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700615
Charles Chanfd48c222017-06-19 00:43:31 -0700616 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700617 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700618 linkService.removeListener(linkListener);
619 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700620 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700621 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100622 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700623 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700624 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700625
Charles Chan2e71ef32017-02-23 15:44:08 -0800626 neighbourResolutionService.unregisterNeighbourHandlers(appId);
627
sangho80f11cb2015-04-01 13:05:26 -0700628 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700629 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700630 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700631 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700632 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700633 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700634
Saurav Das261c3002017-06-13 15:35:54 -0700635 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800636 vlanNextObjStore.destroy();
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000637 macVlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700638 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700639 tunnelStore.destroy();
640 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100641
642 mcastHandler.terminate();
piercf557922019-05-17 20:47:06 +0200643 hostHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700644 log.info("Stopped");
645 }
646
Charles Chan873661e2017-11-30 15:37:50 -0800647 @Modified
648 private void modified(ComponentContext context) {
649 Dictionary<?, ?> properties = context.getProperties();
650 if (properties == null) {
651 return;
652 }
653
Ray Milkey48d10c02018-10-24 10:04:03 -0700654 String strActiveProbing = Tools.get(properties, PROP_ACTIVE_PROBING);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700655 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800656 if (expectActiveProbing != activeProbing) {
657 activeProbing = expectActiveProbing;
658 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
659 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700660
Ray Milkeye96d0de2018-11-02 17:12:21 -0700661
662 String strSymmetricProbing = Tools.get(properties, PROP_SYMMETRIC_PROBING);
663 boolean expectSymmetricProbing = Boolean.parseBoolean(strSymmetricProbing);
Mayank Tiwarif7942402018-10-29 18:27:35 -0400664 if (expectSymmetricProbing != symmetricProbing) {
665 symmetricProbing = expectSymmetricProbing;
666 log.info("{} symmetric probing", symmetricProbing ? "Enabling" : "Disabling");
667 }
668
Ray Milkey48d10c02018-10-24 10:04:03 -0700669 String strSingleHomedDown = Tools.get(properties, PROP_SINGLE_HOMED_DOWN);
Saurav Dasec683dc2018-04-27 18:42:30 -0700670 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
671 if (expectSingleHomedDown != singleHomedDown) {
672 singleHomedDown = expectSingleHomedDown;
673 log.info("{} downing of single homed hosts for lost uplinks",
674 singleHomedDown ? "Enabling" : "Disabling");
675 if (singleHomedDown && linkHandler != null) {
676 hostService.getHosts().forEach(host -> host.locations()
677 .forEach(loc -> {
678 if (interfaceService.isConfigured(loc)) {
679 linkHandler.checkUplinksForHost(loc);
680 }
681 }));
682 } else {
683 log.warn("Disabling singleHomedDown does not re-enable already "
684 + "downed ports for single-homed hosts");
685 }
686 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700687
Ray Milkey48d10c02018-10-24 10:04:03 -0700688 String strRespondToUnknownHosts = Tools.get(properties, PROP_RESPOND_TO_UNKNOWN_HOSTS);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700689 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
690 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
691 respondToUnknownHosts = expectRespondToUnknownHosts;
692 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
693 }
Charles Chan4eb73bb2018-07-19 14:55:31 -0700694
Ray Milkey48d10c02018-10-24 10:04:03 -0700695 String strRouteDoubleTaggedHosts = Tools.get(properties, PROP_ROUTE_DOUBLE_TAGGED_HOSTS);
Charles Chanfbca55e2018-07-24 16:40:35 -0700696 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
697 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
698 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
699 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan4eb73bb2018-07-19 14:55:31 -0700700
Charles Chanfbca55e2018-07-24 16:40:35 -0700701 if (routeDoubleTaggedHosts) {
Charles Chan4eb73bb2018-07-19 14:55:31 -0700702 hostHandler.populateAllDoubleTaggedHost();
703 } else {
704 hostHandler.revokeAllDoubleTaggedHost();
705 }
706 }
Saurav Das9bf49582018-08-13 15:34:26 -0700707
Ray Milkey48d10c02018-10-24 10:04:03 -0700708 String strDefaultInternalVlan = Tools.get(properties, PROP_DEFAULT_INTERNAL_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700709 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
710 if (defIntVlan != defaultInternalVlan) {
711 if (canUseVlanId(defIntVlan)) {
712 log.warn("Default internal vlan value changed from {} to {}.. "
713 + "re-programming filtering rules, but NOT any groups already "
714 + "created with the former value", defaultInternalVlan, defIntVlan);
715 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
716 defaultInternalVlan = defIntVlan;
717 routingRulePopulator
718 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
719 VlanId.vlanId((short) defIntVlan));
720 } else {
721 log.warn("Cannot change default internal vlan to unusable "
722 + "value {}", defIntVlan);
723 }
724 }
725
Ray Milkey48d10c02018-10-24 10:04:03 -0700726 String strPwTxpVlan = Tools.get(properties, PROP_PW_TRANSPORT_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700727 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
728 if (pwTxpVlan != pwTransportVlan) {
729 if (canUseVlanId(pwTxpVlan)) {
730 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
731 + "re-programming filtering rules, but NOT any groups already "
732 + "created with the former value", pwTransportVlan,
733 pwTxpVlan);
734 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
735 pwTransportVlan = pwTxpVlan;
736 routingRulePopulator
737 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
738 VlanId.vlanId((short) pwTxpVlan));
739 } else {
740 log.warn("Cannot change pseudowire transport vlan to unusable "
741 + "value {}", pwTxpVlan);
742 }
743 }
744
psneha86e60d32019-03-26 06:31:41 -0400745 String strRouteSimplification = Tools.get(properties, PROP_ROUTE_SIMPLIFICATION);
746 boolean expectRouteSimplification = Boolean.parseBoolean(strRouteSimplification);
747 if (expectRouteSimplification != routeSimplification) {
748 routeSimplification = expectRouteSimplification;
749 log.info("{} route simplification", routeSimplification ? "Enabling" : "Disabling");
750 }
751
Saurav Das9bf49582018-08-13 15:34:26 -0700752 }
753
754 /**
Danny Chang44a7b952020-09-08 15:27:04 -0700755 * Removes all packet requests.
756 */
757 private void cancelPackets() {
758 if (routingRulePopulator == null) {
759 return;
760 }
761 log.info("Removing packet requests.");
762 routingRulePopulator.revokePacketsPunts();
763 }
764
765 /**
Saurav Das9bf49582018-08-13 15:34:26 -0700766 * Returns true if given vlan id is not being used in the system currently,
767 * either as one of the default system wide vlans or as one of the
768 * configured interface vlans.
769 *
770 * @param vlanId given vlan id
771 * @return true if vlan is not currently in use
772 */
773 public boolean canUseVlanId(int vlanId) {
774 if (vlanId >= 4095 || vlanId <= 1) {
775 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
776 vlanId);
777 return false;
778 }
779
780 VlanId vid = VlanId.vlanId((short) vlanId);
781 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
782 log.warn("Vlan id {} value is already in use system-wide. "
783 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
784 getDefaultInternalVlan(), getPwTransportVlan());
785 return false;
786 }
787
788 if (interfaceService.inUse(vid)) {
789 log.warn("Vlan id {} value is already in use on a configured "
790 + "interface in the system", vlanId);
791 return false;
792 }
793 return true;
794 }
795
pierventre4f68ffa2021-03-09 22:52:14 +0100796 @Override
Saurav Das9bf49582018-08-13 15:34:26 -0700797 public VlanId getDefaultInternalVlan() {
798 return VlanId.vlanId((short) defaultInternalVlan);
799 }
800
801 /**
802 * Returns the Vlan id used to transport pseudowire traffic across the
803 * network.
804 *
805 * @return the pseudowire transport vlan id
806 */
807 public VlanId getPwTransportVlan() {
808 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan873661e2017-11-30 15:37:50 -0800809 }
810
sangho27462c62015-05-14 00:39:53 -0700811 @Override
812 public List<Tunnel> getTunnels() {
813 return tunnelHandler.getTunnels();
814 }
815
816 @Override
sanghobd812f82015-06-29 14:58:47 -0700817 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
818 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700819 }
820
821 @Override
sanghobd812f82015-06-29 14:58:47 -0700822 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700823 for (Policy policy: policyHandler.getPolicies()) {
824 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
825 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
826 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
827 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700828 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700829 }
830 }
831 }
sanghobd812f82015-06-29 14:58:47 -0700832 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700833 }
834
835 @Override
sanghobd812f82015-06-29 14:58:47 -0700836 public PolicyHandler.Result removePolicy(Policy policy) {
837 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700838 }
839
840 @Override
sanghobd812f82015-06-29 14:58:47 -0700841 public PolicyHandler.Result createPolicy(Policy policy) {
842 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700843 }
844
845 @Override
846 public List<Policy> getPolicies() {
847 return policyHandler.getPolicies();
848 }
849
Saurav Das07c74602016-04-27 18:35:50 -0700850 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700851 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
852 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700853 }
854
855 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800856 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700857 return l2TunnelHandler.getL2Tunnels();
858 }
859
860 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800861 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700862 return l2TunnelHandler.getL2Policies();
863 }
864
Saurav Dasdebcf882018-04-06 20:16:01 -0700865 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700866 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700867 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
868
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700869 // get both added and pending pseudowires
870 List<L2TunnelDescription> pseudowires = new ArrayList<>();
871 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
872 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700873 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700874
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700875 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
876
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700877 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
878 L2TunnelHandler.Result res;
879 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
880 res = addPseudowire(pw);
881 if (res != L2TunnelHandler.Result.SUCCESS) {
882 log.error("Pseudowire with id {} can not be instantiated !", res);
883 retRes = res;
884 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700885 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700886
887 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700888 }
889
890 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800891 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700892 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700893 }
894
895 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800896 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700897 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700898 }
899
900 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700901 public void rerouteNetwork() {
pierventrec80a5052021-05-20 12:56:38 +0200902 cfgListener.configureNetworkAndDrainEvents();
Saurav Das07c74602016-04-27 18:35:50 -0700903 }
904
Charles Chand7844e52016-10-20 17:02:44 -0700905 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800906 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
907 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800908 deviceConfiguration.getRouters().forEach(device ->
909 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700910 return deviceSubnetMap;
911 }
912
Saurav Das62ae6792017-05-15 15:34:25 -0700913
914 @Override
915 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
916 if (defaultRoutingHandler != null) {
917 return defaultRoutingHandler.getCurrentEmcpSpgMap();
918 } else {
919 return null;
920 }
921 }
922
923 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700924 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das261c3002017-06-13 15:35:54 -0700925 if (dsNextObjStore != null) {
926 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700927 } else {
928 return ImmutableMap.of();
929 }
930 }
931
Saurav Dasfbe74572017-08-03 18:30:35 -0700932 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700933 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
934 if (vlanNextObjStore != null) {
935 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
936 } else {
937 return ImmutableMap.of();
938 }
939 }
940
941 @Override
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000942 public ImmutableMap<MacVlanNextObjectiveStoreKey, Integer> getMacVlanNextObjStore() {
943 if (macVlanNextObjStore != null) {
944 return ImmutableMap.copyOf(macVlanNextObjStore.entrySet());
945 } else {
946 return ImmutableMap.of();
947 }
948 }
949
950 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700951 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
952 if (portNextObjStore != null) {
953 return ImmutableMap.copyOf(portNextObjStore.entrySet());
954 } else {
955 return ImmutableMap.of();
956 }
957 }
958
959 @Override
960 public ImmutableMap<String, NextObjective> getPwInitNext() {
961 if (l2TunnelHandler != null) {
962 return l2TunnelHandler.getInitNext();
963 } else {
964 return ImmutableMap.of();
965 }
966 }
967
968 @Override
969 public ImmutableMap<String, NextObjective> getPwTermNext() {
970 if (l2TunnelHandler != null) {
971 return l2TunnelHandler.getTermNext();
972 } else {
973 return ImmutableMap.of();
974 }
975 }
976
977 @Override
978 public void invalidateNextObj(int nextId) {
979 if (dsNextObjStore != null) {
980 dsNextObjStore.entrySet().forEach(e -> {
981 if (e.getValue().nextId() == nextId) {
982 dsNextObjStore.remove(e.getKey());
983 }
984 });
985 }
986 if (vlanNextObjStore != null) {
987 vlanNextObjStore.entrySet().forEach(e -> {
988 if (e.getValue() == nextId) {
989 vlanNextObjStore.remove(e.getKey());
990 }
991 });
992 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000993 if (macVlanNextObjStore != null) {
994 macVlanNextObjStore.entrySet().forEach(e -> {
995 if (e.getValue() == nextId) {
996 macVlanNextObjStore.remove(e.getKey());
997 }
998 });
999 }
Charles Chan0b1dd7e2018-08-19 19:21:46 -07001000 if (portNextObjStore != null) {
1001 portNextObjStore.entrySet().forEach(e -> {
1002 if (e.getValue() == nextId) {
1003 portNextObjStore.remove(e.getKey());
1004 }
1005 });
1006 }
1007 if (mcastHandler != null) {
1008 mcastHandler.removeNextId(nextId);
1009 }
1010 if (l2TunnelHandler != null) {
1011 l2TunnelHandler.removeNextId(nextId);
1012 }
1013 if (xconnectService != null) {
1014 xconnectService.removeNextId(nextId);
1015 }
1016 }
1017
1018 @Override
Saurav Dasfbe74572017-08-03 18:30:35 -07001019 public void verifyGroups(DeviceId id) {
1020 DefaultGroupHandler gh = groupHandlerMap.get(id);
1021 if (gh != null) {
1022 gh.triggerBucketCorrector();
1023 }
1024 }
1025
Saurav Das6430f412018-01-25 09:49:01 -08001026 @Override
1027 public ImmutableMap<Link, Boolean> getSeenLinks() {
1028 return linkHandler.getSeenLinks();
1029 }
1030
1031 @Override
1032 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
1033 return linkHandler.getDownedPorts();
1034 }
1035
Pier Luigi0f9635b2018-01-15 18:06:43 +01001036 @Override
1037 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -07001038 return mcastHandler.getNextIds(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +01001039 }
1040
1041 @Override
Piere99511d2018-04-19 16:47:06 +02001042 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
1043 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
1044 }
1045
1046 @Override
Pier71c55772018-04-17 17:25:22 +02001047 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
1048 ConnectPoint sourcecp) {
1049 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
1050 }
1051
1052 @Override
Pierdb27b8d2018-04-17 16:29:56 +02001053 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
1054 return mcastHandler.getMcastLeaders(mcastIp);
1055 }
1056
Charles Chanb13e0702018-04-17 18:56:53 -07001057 @Override
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001058 public Map<DeviceId, List<McastFilteringObjStoreKey>> getMcastFilters() {
1059 return mcastHandler.getMcastFilters();
1060 }
1061
1062 @Override
Charles Chanb13e0702018-04-17 18:56:53 -07001063 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
1064 return defaultRoutingHandler == null ? ImmutableMap.of() :
1065 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
1066 }
1067
1068 @Override
1069 public Map<DeviceId, Boolean> getShouldProgramCache() {
1070 return defaultRoutingHandler == null ? ImmutableMap.of() :
1071 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
1072 }
1073
Charles Chan8d316332018-06-19 20:31:57 -07001074 @Override
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301075 public boolean shouldProgram(DeviceId deviceId) {
1076 return defaultRoutingHandler.shouldProgram(deviceId);
1077 }
1078
1079 @Override
Charles Chan12a8a842020-02-14 13:23:57 -08001080 public boolean isRoutingStable() {
1081 return defaultRoutingHandler.isRoutingStable();
1082 }
1083
1084 @Override
1085 public void initHost(DeviceId deviceId) {
1086 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1087 }
1088
1089 @Override
1090 public void initRoute(DeviceId deviceId) {
1091 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
1092 }
1093
1094 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -07001095 public ApplicationId appId() {
1096 return appId;
1097 }
1098
1099 /**
1100 * Returns the device configuration.
1101 *
1102 * @return device configuration
1103 */
1104 public DeviceConfiguration deviceConfiguration() {
1105 return deviceConfiguration;
1106 }
1107
1108 /**
Saurav Das261c3002017-06-13 15:35:54 -07001109 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -07001110 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001111 *
1112 * @return next objective ID store
1113 */
Saurav Das261c3002017-06-13 15:35:54 -07001114 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1115 dsNextObjStore() {
1116 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -07001117 }
1118
1119 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001120 * Per device next objective ID store with (device id + vlanid) as key.
1121 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001122 *
1123 * @return vlan next object store
1124 */
1125 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1126 return vlanNextObjStore;
1127 }
1128
1129 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001130 * Per device next objective ID store with (device id + MAC address + vlan) as key.
1131 * Used to keep track on L3 Unicast group information for indirect hosts.
1132 *
1133 * @return mac vlan next object store
1134 */
1135 public EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer> macVlanNextObjStore() {
1136 return macVlanNextObjStore;
1137 }
1138
1139 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001140 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001141 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Ray Milkeyb85de082017-04-05 09:42:04 -07001142 *
1143 * @return port next object store.
1144 */
1145 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1146 return portNextObjStore;
1147 }
1148
1149 /**
Saurav Das261c3002017-06-13 15:35:54 -07001150 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1151 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -07001152 *
1153 * @return MPLS-ECMP value
1154 */
1155 public boolean getMplsEcmp() {
1156 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1157 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1158 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1159 }
1160
1161 /**
sangho80f1f892015-05-19 11:57:42 -07001162 * Returns the tunnel object with the tunnel ID.
1163 *
1164 * @param tunnelId Tunnel ID
1165 * @return Tunnel reference
1166 */
sangho27462c62015-05-14 00:39:53 -07001167 public Tunnel getTunnel(String tunnelId) {
1168 return tunnelHandler.getTunnel(tunnelId);
1169 }
1170
Charles Chan8d316332018-06-19 20:31:57 -07001171 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +01001172 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -07001173 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1174 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -07001175 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1176 }
1177
Charles Chan8d316332018-06-19 20:31:57 -07001178 @Override
1179 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001180 SegmentRoutingDeviceConfig deviceConfig =
1181 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1182 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1183 }
Charles Chan8d316332018-06-19 20:31:57 -07001184
1185 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -07001186 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001187 SegmentRoutingDeviceConfig deviceConfig =
1188 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1189 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1190 }
1191
Charles Chan12a8a842020-02-14 13:23:57 -08001192 @Override
1193 public Set<PortNumber> getInfraPorts(DeviceId deviceId) {
1194 return deviceService.getPorts(deviceId).stream()
1195 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1196 .filter(cp -> interfaceService.getInterfacesByPort(cp).isEmpty())
1197 .map(ConnectPoint::port)
1198 .collect(Collectors.toSet());
1199 }
1200
1201 @Override
1202 public Set<PortNumber> getEdgePorts(DeviceId deviceId) {
1203 return deviceService.getPorts(deviceId).stream()
1204 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1205 .filter(cp -> !interfaceService.getInterfacesByPort(cp).isEmpty() &&
1206 !cp.port().equals(getPairLocalPort(deviceId).orElse(null)))
1207 .map(ConnectPoint::port)
1208 .collect(Collectors.toSet());
1209 }
1210
pierventre30368ab2021-02-24 23:23:22 +01001211 @Override
1212 public List<DeviceId> getEdgeDeviceIds() {
1213 return deviceConfiguration.getEdgeDeviceIds();
1214 }
1215
pierventre4f68ffa2021-03-09 22:52:14 +01001216 @Override
Charles Chana2401452021-06-03 15:57:48 -07001217 public List<DeviceId> getInfraDeviceIds() {
1218 return deviceConfiguration.getInfraDeviceIds();
1219 }
1220
1221 @Override
pierventre4f68ffa2021-03-09 22:52:14 +01001222 public MacAddress getDeviceMacAddress(DeviceId deviceId) throws DeviceConfigNotFoundException {
1223 return deviceConfiguration.getDeviceMac(deviceId);
1224 }
1225
Charles Chan3ed34d82017-06-22 18:03:14 -07001226 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -07001227 * Returns locations of given resolved route.
1228 *
1229 * @param resolvedRoute resolved route
1230 * @return locations of nexthop. Might be empty if next hop is not found
1231 */
Charles Chan19b70032019-04-17 14:20:26 -07001232 public Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
Charles Chanf0ae41e2017-08-23 13:55:39 -07001233 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1234 return Optional.ofNullable(hostService.getHost(hostId))
1235 .map(Host::locations).orElse(Sets.newHashSet())
1236 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1237 }
1238
1239 /**
Charles Chan90772a72017-02-08 15:52:08 -08001240 * Returns vlan port map of given device.
1241 *
1242 * @param deviceId device id
1243 * @return vlan-port multimap
1244 */
1245 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1246 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1247
1248 interfaceService.getInterfaces().stream()
1249 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1250 .forEach(intf -> {
1251 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -07001252 intf.vlanTagged().forEach(vlanTagged ->
1253 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1254 );
Charles Chan90772a72017-02-08 15:52:08 -08001255 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1256 });
1257 vlanPortMap.removeAll(VlanId.NONE);
1258
1259 return vlanPortMap;
1260 }
1261
1262 /**
Charles Chan10b0fb72017-02-02 16:20:42 -08001263 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -08001264 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -07001265 *
1266 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -08001267 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -08001268 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -07001269 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001270 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -07001271 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -08001272 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1273 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -07001274 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -08001275 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -08001276 + "device {} not found", deviceId);
1277 return -1;
1278 }
1279 }
1280
1281 /**
1282 * Returns the next objective ID for the given portNumber, given the treatment.
1283 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -07001284 * would result in different objectives. If the next object does not exist,
1285 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -08001286 *
1287 * @param deviceId Device ID
1288 * @param portNum port number on device for which NextObjective is queried
1289 * @param treatment the actions to apply on the packets (should include outport)
1290 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -07001291 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -07001292 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -08001293 */
1294 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1295 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -07001296 TrafficSelector meta,
1297 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -08001298 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1299 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -07001300 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -08001301 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -08001302 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1303 + " not found", deviceId);
1304 return -1;
1305 }
1306 }
1307
Saurav Das62ae6792017-05-15 15:34:25 -07001308 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001309 * Returns the next Objective ID for the given mac and vlan, given the treatment.
1310 * There could be multiple different treatments to the same outport, which
1311 * would result in different objectives. If the next object does not exist,
1312 * and should be created, a new one is created and its id is returned.
1313 *
1314 * @param deviceId Device ID
1315 * @param macAddr mac of host for which Next ID is required.
1316 * @param vlanId vlan of host for which Next ID is required.
Ruchi Sahota07869322019-05-09 17:26:14 -04001317 * @param port port with which to create the Next Obj.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001318 * @param createIfMissing true if a next object should be created if not found
1319 * @return next objective ID or -1 if an error occurred during retrieval or creation
1320 */
1321 public int getMacVlanNextObjectiveId(DeviceId deviceId, MacAddress macAddr, VlanId vlanId,
Ruchi Sahota07869322019-05-09 17:26:14 -04001322 PortNumber port, boolean createIfMissing) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001323 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1324 if (ghdlr != null) {
Ruchi Sahota07869322019-05-09 17:26:14 -04001325 return ghdlr.getMacVlanNextObjectiveId(macAddr, vlanId, port, createIfMissing);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001326 } else {
1327 log.warn("getMacVlanNextObjectiveId query - groupHandler for device {}"
1328 + " not found", deviceId);
1329 return -1;
1330 }
1331 }
1332
1333 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001334 * Updates the next objective for the given nextId .
1335 *
1336 * @param deviceId Device ID
1337 * @param hostMac mac of host for which Next obj is to be updated.
1338 * @param hostVlanId vlan of host for which Next obj is to be updated.
1339 * @param port port with which to update the Next Obj.
1340 * @param nextId of Next Obj which needs to be updated.
1341 */
1342 public void updateMacVlanTreatment(DeviceId deviceId, MacAddress hostMac,
pierventrea3989be2021-01-08 16:43:17 +01001343 VlanId hostVlanId, PortNumber port, int nextId) {
pierf0e37ec2019-11-26 11:48:48 +01001344 // Check if we are the king of this device
1345 // just one instance should perform this update
1346 if (!defaultRoutingHandler.shouldProgram(deviceId)) {
1347 log.debug("This instance is not handling the routing towards the "
1348 + "device {}", deviceId);
1349 return;
1350 }
1351 // Get the handler and perform the update
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001352 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1353 if (ghdlr != null) {
1354 ghdlr.updateL3UcastGroupBucket(hostMac, hostVlanId, port, nextId);
1355 } else {
1356 log.warn("updateL3UcastGroupBucket query - groupHandler for device {}"
1357 + " not found", deviceId);
1358 }
1359 }
1360
1361
1362 /**
Saurav Das62ae6792017-05-15 15:34:25 -07001363 * Returns the group handler object for the specified device id.
1364 *
1365 * @param devId the device identifier
1366 * @return the groupHandler object for the device id, or null if not found
1367 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001368 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001369 return groupHandlerMap.get(devId);
1370 }
1371
1372 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001373 * Returns the default routing handler object.
1374 *
1375 * @return the default routing handler object
1376 */
1377 public DefaultRoutingHandler getRoutingHandler() {
1378 return defaultRoutingHandler;
1379 }
1380
sangho80f11cb2015-04-01 13:05:26 -07001381 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001382 @Override
1383 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001384 packetExecutor.execute(() -> processPacketInternal(context));
1385 }
sangho80f11cb2015-04-01 13:05:26 -07001386
Charles Chan77cdde42018-05-08 21:35:50 -07001387 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001388 if (context.isHandled()) {
1389 return;
1390 }
1391
1392 InboundPacket pkt = context.inPacket();
1393 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001394
1395 if (ethernet == null) {
1396 return;
1397 }
1398
Saurav Das261c3002017-06-13 15:35:54 -07001399 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1400 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001401 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001402 log.warn("Received unexpected ARP packet on {}",
1403 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001404 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001405 return;
sangho80f11cb2015-04-01 13:05:26 -07001406 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001407 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1408 //ipHandler.addToPacketBuffer(ipv4Packet);
1409 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1410 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001411 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001412 // NOTE: We don't support IP learning at this moment so this
1413 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001414 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001415 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001416 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1417 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001418 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001419 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001420 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1421 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1422 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1423 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1424 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1425 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001426 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001427 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001428 }
1429 } else {
1430 // NOTE: We don't support IP learning at this moment so this
1431 // is not necessary. Also it causes duplication of DHCPv6 packets.
1432 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1433 }
sangho80f11cb2015-04-01 13:05:26 -07001434 }
1435 }
1436 }
1437
sangho80f11cb2015-04-01 13:05:26 -07001438 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001439 private Event event;
1440
1441 InternalEventHandler(Event event) {
1442 this.event = event;
1443 }
1444
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001445 @Override
sangho80f11cb2015-04-01 13:05:26 -07001446 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001447 try {
1448 // TODO We should also change SR routing and PW to listen to TopologyEvents
1449 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1450 event.type() == LinkEvent.Type.LINK_UPDATED) {
1451 linkHandler.processLinkAdded((Link) event.subject());
1452 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1453 linkHandler.processLinkRemoved((Link) event.subject());
1454 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1455 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1456 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1457 DeviceId deviceId = ((Device) event.subject()).id();
1458 if (deviceService.isAvailable(deviceId)) {
1459 log.info("** DEVICE UP Processing device event {} "
1460 + "for available device {}",
1461 event.type(), ((Device) event.subject()).id());
1462 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001463 } else {
Charles Chanb8f3af52018-08-29 21:21:51 -07001464 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1465 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1466 // The device will later on being marked as available once the pipeline is pushed
1467 // to the device.
1468 log.info("** DEVICE ADDED but unavailable. Ignore");
1469 return;
1470 }
Charles Chan52003922018-04-05 16:31:15 -07001471 log.info(" ** DEVICE DOWN Processing device event {}"
1472 + " for unavailable device {}",
1473 event.type(), ((Device) event.subject()).id());
1474 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001475 }
Charles Chan52003922018-04-05 16:31:15 -07001476 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1477 // typically these calls come when device is added first time
1478 // so port filtering rules are handled at the device_added event.
1479 // port added calls represent all ports on the device,
1480 // enabled or not.
1481 log.trace("** PORT ADDED {}/{} -> {}",
1482 ((DeviceEvent) event).subject().id(),
1483 ((DeviceEvent) event).port().number(),
1484 event.type());
1485 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1486 // these calls happen for every subsequent event
1487 // ports enabled, disabled, switch goes away, comes back
1488 log.info("** PORT UPDATED {}/{} -> {}",
1489 event.subject(),
1490 ((DeviceEvent) event).port(),
1491 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001492 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001493 ((DeviceEvent) event).port());
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001494 mcastHandler.processPortUpdate(((Device) event.subject()),
1495 ((DeviceEvent) event).port());
Charles Chan52003922018-04-05 16:31:15 -07001496 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1497 // Process topology event, needed for all modules relying on
1498 // topology service for path computation
1499 TopologyEvent topologyEvent = (TopologyEvent) event;
1500 log.info("Processing topology event {}, topology age {}, reasons {}",
1501 event.type(), topologyEvent.subject().time(),
1502 topologyEvent.reasons().size());
1503 topologyHandler.processTopologyChange(topologyEvent.reasons());
1504 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1505 hostHandler.processHostAddedEvent((HostEvent) event);
1506 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1507 hostHandler.processHostMovedEvent((HostEvent) event);
1508 routeHandler.processHostMovedEvent((HostEvent) event);
Charles Chana2ccb582019-11-25 09:47:22 -08001509 } else if (event.type() == HostEvent.Type.HOST_AUX_MOVED) {
1510 hostHandler.processHostMovedEvent((HostEvent) event);
1511 // TODO RouteHandler also needs to process this event in order to
1512 // support nexthops that has auxLocations
Charles Chan52003922018-04-05 16:31:15 -07001513 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1514 hostHandler.processHostRemovedEvent((HostEvent) event);
1515 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1516 hostHandler.processHostUpdatedEvent((HostEvent) event);
1517 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1518 routeHandler.processRouteAdded((RouteEvent) event);
1519 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1520 routeHandler.processRouteUpdated((RouteEvent) event);
1521 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1522 routeHandler.processRouteRemoved((RouteEvent) event);
1523 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1524 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1525 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1526 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1527 event.type() == McastEvent.Type.SINKS_ADDED ||
1528 event.type() == McastEvent.Type.SINKS_REMOVED ||
1529 event.type() == McastEvent.Type.ROUTE_ADDED ||
1530 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1531 mcastHandler.processMcastEvent((McastEvent) event);
1532 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1533 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1534 Class configClass = netcfgEvent.configClass();
1535 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1536 appCfgHandler.processAppConfigAdded(netcfgEvent);
1537 log.info("App config event .. configuring network");
pierventrec80a5052021-05-20 12:56:38 +02001538 cfgListener.configureNetworkAndDrainEvents();
Charles Chan52003922018-04-05 16:31:15 -07001539 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1540 log.info("Segment Routing Device Config added for {}", event.subject());
pierventrec80a5052021-05-20 12:56:38 +02001541 cfgListener.configureNetworkAndDrainEvents();
Charles Chan52003922018-04-05 16:31:15 -07001542 } else if (configClass.equals(InterfaceConfig.class)) {
1543 log.info("Interface Config added for {}", event.subject());
pierventrec80a5052021-05-20 12:56:38 +02001544 cfgListener.configureNetworkAndDrainEvents();
Charles Chan52003922018-04-05 16:31:15 -07001545 } else {
1546 log.error("Unhandled config class: {}", configClass);
1547 }
1548 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1549 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1550 Class configClass = netcfgEvent.configClass();
1551 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1552 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1553 log.info("App config event .. configuring network");
pierventrec80a5052021-05-20 12:56:38 +02001554 cfgListener.configureNetworkAndDrainEvents();
Charles Chan52003922018-04-05 16:31:15 -07001555 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1556 log.info("Segment Routing Device Config updated for {}", event.subject());
1557 createOrUpdateDeviceConfiguration();
Charles Chan52003922018-04-05 16:31:15 -07001558 } else if (configClass.equals(InterfaceConfig.class)) {
1559 log.info("Interface Config updated for {}", event.subject());
1560 createOrUpdateDeviceConfiguration();
1561 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1562 (InterfaceConfig) netcfgEvent.prevConfig().get());
1563 } else {
1564 log.error("Unhandled config class: {}", configClass);
1565 }
1566 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1567 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1568 Class configClass = netcfgEvent.configClass();
1569 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1570 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1571 log.info("App config event .. configuring network");
pierventrec80a5052021-05-20 12:56:38 +02001572 cfgListener.configureNetworkAndDrainEvents();
Charles Chan52003922018-04-05 16:31:15 -07001573 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1574 // TODO Handle sr device config removal
1575 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
Charles Chan52003922018-04-05 16:31:15 -07001576 } else if (configClass.equals(InterfaceConfig.class)) {
1577 // TODO Handle interface removal
1578 log.info("InterfaceConfig removal is not handled in current implementation");
1579 } else {
1580 log.error("Unhandled config class: {}", configClass);
1581 }
Saurav Das00e553b2018-04-21 17:19:48 -07001582 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1583 MastershipEvent me = (MastershipEvent) event;
1584 DeviceId deviceId = me.subject();
1585 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1586 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1587 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1588 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1589 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1590 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chana2401452021-06-03 15:57:48 -07001591
Charles Chan52003922018-04-05 16:31:15 -07001592 } else {
1593 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001594 }
Charles Chan52003922018-04-05 16:31:15 -07001595 } catch (Exception e) {
1596 log.error("SegmentRouting event handler thread thrown an exception: {}",
1597 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001598 }
sangho80f11cb2015-04-01 13:05:26 -07001599 }
1600 }
1601
Saurav Dase6c448a2018-01-18 12:07:33 -08001602 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001603 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001604
1605 // NOTE: Punt ARP/NDP even when the device is not configured.
1606 // Host learning without network config is required for CORD config generator.
1607 routingRulePopulator.populateIpPunts(device.id());
1608 routingRulePopulator.populateArpNdpPunts(device.id());
1609
Charles Chan319d1a22015-11-03 10:42:14 -08001610 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001611 log.warn("Device configuration unavailable. Device {} will be "
1612 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001613 return;
1614 }
Charles Chan72779502016-04-23 17:36:10 -07001615 processDeviceAddedInternal(device.id());
1616 }
1617
1618 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001619 // Irrespective of whether the local is a MASTER or not for this device,
1620 // we need to create a SR-group-handler instance. This is because in a
1621 // multi-instance setup, any instance can initiate forwarding/next-objectives
1622 // for any switch (even if this instance is a SLAVE or not even connected
1623 // to the switch). To handle this, a default-group-handler instance is necessary
1624 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001625 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1626 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001627 DefaultGroupHandler groupHandler;
1628 try {
1629 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001630 createGroupHandler(deviceId,
1631 appId,
1632 deviceConfiguration,
1633 linkService,
1634 flowObjectiveService,
1635 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001636 } catch (DeviceConfigNotFoundException e) {
1637 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1638 return;
1639 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001640 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001641 deviceId);
1642 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001643 }
Saurav Dasb149be12016-06-07 10:08:06 -07001644
Charles Chan72779502016-04-23 17:36:10 -07001645 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001646 defaultRoutingHandler.populatePortAddressingRules(deviceId);
pierf331a492020-01-07 15:39:39 +01001647 defaultRoutingHandler.purgeSeenBeforeRoutes(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001648 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001649 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001650 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan12a8a842020-02-14 13:23:57 -08001651 phasedRecoveryService.init(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001652 }
Charles Chan82ab1932016-01-30 23:22:37 -08001653
Charles Chandebfea32016-10-24 14:52:01 -07001654 appCfgHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001655 }
1656
Saurav Dasc3604f12016-03-23 11:22:49 -07001657 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001658 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001659 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001660 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001661 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001662 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001663 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001664 macVlanNextObjStore.entrySet().stream()
1665 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1666 .forEach(entry -> macVlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001667 portNextObjStore.entrySet().stream()
1668 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001669 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001670 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001671
Saurav Dasfbe74572017-08-03 18:30:35 -07001672 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1673 if (gh != null) {
1674 gh.shutdown();
1675 }
Saurav Das62ae6792017-05-15 15:34:25 -07001676 // Note that a switch going down is associated with all of its links
1677 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001678 // while the link-downs are ignored. We cannot rely on the ordering of
1679 // events - i.e we cannot expect all link-downs to come before the
1680 // switch down - so we purge all seen-links for the switch before
1681 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001682 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001683 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001684 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001685
1686 // Cleanup all internal groupHandler stores for this device. Should be
1687 // done after all rerouting or rehashing has been completed
1688 groupHandlerMap.entrySet()
1689 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Charles Chan12a8a842020-02-14 13:23:57 -08001690
1691 phasedRecoveryService.reset(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001692 }
1693
Saurav Das49368392018-04-23 18:42:12 -07001694 /**
1695 * Purge the destinationSet nextObjective store of entries with this device
1696 * as key. Erases app-level knowledge of hashed groups in this device.
1697 *
1698 * @param devId the device identifier
1699 */
Saurav Das00e553b2018-04-21 17:19:48 -07001700 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001701 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001702 dsNextObjStore.entrySet().stream()
1703 .filter(entry -> entry.getKey().deviceId().equals(devId))
1704 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1705 }
1706
Saurav Dasec683dc2018-04-27 18:42:30 -07001707 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001708 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Jon Hall5e41a7b2021-01-28 19:42:45 -08001709 log.warn("Device configuration uploading. Not handling port event for "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001710 + "dev: {} port: {}", device.id(), port.number());
1711 return;
1712 }
Saurav Dasf9332192017-02-18 14:05:44 -08001713
Saurav Dasec683dc2018-04-27 18:42:30 -07001714 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1715 lastEdgePortEvent = Instant.now();
1716 }
1717
Saurav Dasf9332192017-02-18 14:05:44 -08001718 if (!mastershipService.isLocalMaster(device.id())) {
Jon Hall5e41a7b2021-01-28 19:42:45 -08001719 log.debug("Not master for dev:{} .. not handling port updated event "
Saurav Dasf9332192017-02-18 14:05:44 -08001720 + "for port {}", device.id(), port.number());
1721 return;
1722 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001723 processPortUpdated(device.id(), port);
1724 }
Saurav Dasf9332192017-02-18 14:05:44 -08001725
Saurav Dasec683dc2018-04-27 18:42:30 -07001726 /**
1727 * Adds or remove filtering rules for the given switchport. If switchport is
1728 * an edge facing port, additionally handles host probing and broadcast
1729 * rules. Must be called by local master of device.
1730 *
1731 * @param deviceId the device identifier
1732 * @param port the port to update
1733 */
1734 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001735 // first we handle filtering rules associated with the port
1736 if (port.isEnabled()) {
1737 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001738 deviceId, port.number());
1739 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001740 } else {
1741 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001742 deviceId, port.number());
1743 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001744 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001745
1746 // portUpdated calls are for ports that have gone down or up. For switch
1747 // to switch ports, link-events should take care of any re-routing or
1748 // group editing necessary for port up/down. Here we only process edge ports
1749 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001750 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001751 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1752 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1753 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001754
Saurav Das3fb28272017-03-04 16:08:47 -08001755 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001756 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001757 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001758 return;
1759 }
Saurav Das3fb28272017-03-04 16:08:47 -08001760 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001761 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001762 }
1763 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001764 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001765 }
1766 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001767 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001768 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001769 }
1770
Saurav Dasec683dc2018-04-27 18:42:30 -07001771 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001772 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001773 boolean portUp = port.isEnabled();
1774 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001775 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001776 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001777 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001778 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001779 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001780 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001781 }
1782
Saurav Dasec683dc2018-04-27 18:42:30 -07001783 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001784 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001785 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001786 } else {
1787 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001788 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001789 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001790 }
1791 }
sangho27462c62015-05-14 00:39:53 -07001792
Charles Chan8ca5a122017-10-20 16:06:55 -07001793 private void createOrUpdateDeviceConfiguration() {
1794 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001795 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001796 deviceConfiguration = new DeviceConfiguration(this);
1797 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001798 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001799 deviceConfiguration.updateConfig();
1800 }
1801 }
1802
Charles Chanfbcb8812018-04-18 18:41:05 -07001803 private void createOrUpdateDefaultRoutingHandler() {
1804 if (defaultRoutingHandler == null) {
1805 log.info("Creating new DefaultRoutingHandler");
1806 defaultRoutingHandler = new DefaultRoutingHandler(this);
1807 } else {
1808 log.info("Updating DefaultRoutingHandler");
1809 defaultRoutingHandler.update(this);
1810 }
1811 }
1812
Pier Ventreb6a7f342016-11-26 21:05:22 -08001813 /**
1814 * Registers the given connect point with the NRS, this is necessary
1815 * to receive the NDP and ARP packets from the NRS.
1816 *
1817 * @param portToRegister connect point to register
1818 */
1819 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001820 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001821 portToRegister,
1822 neighbourHandler,
1823 appId
1824 );
1825 }
1826
Charles Chan72f556a2015-10-05 17:50:33 -07001827 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001828 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001829 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001830
Charles Chanb7f75ac2016-01-11 18:28:54 -08001831 /**
1832 * Constructs the internal network config listener.
1833 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001834 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001835 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001836 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001837 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001838 }
1839
Charles Chanb7f75ac2016-01-11 18:28:54 -08001840 /**
1841 * Reads network config and initializes related data structure accordingly.
1842 */
Charles Chan873661e2017-11-30 15:37:50 -08001843 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001844 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001845
1846 // Setting handling of network configuration events completable future
1847 // The completable future is needed because of the async behaviour of the configureNetwork,
1848 // listener registration and event arrival
1849 // Enables us to buffer the events and execute them when the configure network is done.
Ray Milkey521e4392018-11-16 15:15:14 -08001850 synchronized (networkConfigCompletionLock) {
1851 networkConfigCompletion = new CompletableFuture<>();
Andrea Campanella060cad82018-04-17 12:09:34 +02001852
Ray Milkey521e4392018-11-16 15:15:14 -08001853 // add a small delay to absorb multiple network config added notifications
1854 if (!programmingScheduled.get()) {
1855 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1856 programmingScheduled.set(true);
1857 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1858 }
1859
1860 createOrUpdateDeviceConfiguration();
1861
1862 arpHandler = new ArpHandler(srManager);
1863 icmpHandler = new IcmpHandler(srManager);
1864 ipHandler = new IpHandler(srManager);
1865 routingRulePopulator = new RoutingRulePopulator(srManager);
1866 createOrUpdateDefaultRoutingHandler();
1867
1868 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1869 groupHandlerMap, tunnelStore);
1870 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1871 flowObjectiveService,
1872 tunnelHandler, policyStore);
1873 networkConfigCompletion.complete(true);
Andrea Campanella060cad82018-04-17 12:09:34 +02001874 }
1875
Charles Chan72779502016-04-23 17:36:10 -07001876 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001877
Charles Chane7c61022015-10-07 14:21:45 -07001878 }
1879
pierventrec80a5052021-05-20 12:56:38 +02001880 /**
1881 * Reads network config, initializes related data structure accordingly
1882 * and drain buffered events if needed.
1883 */
1884 void configureNetworkAndDrainEvents() {
1885 configureNetwork();
1886 drainEvents();
1887 }
1888
Charles Chan72f556a2015-10-05 17:50:33 -07001889 @Override
1890 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001891 if (mainEventExecutor == null) {
1892 return;
1893 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001894 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan3f4aca62018-03-21 16:57:47 -07001895 switch (event.type()) {
1896 case CONFIG_ADDED:
1897 case CONFIG_UPDATED:
1898 case CONFIG_REMOVED:
Andrea Campanella060cad82018-04-17 12:09:34 +02001899 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
Charles Chan152dd942020-07-21 15:33:31 -07001900 log.debug("Process netcfg {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001901 mainEventExecutor.execute(new InternalEventHandler(event));
1902 } else {
Charles Chan152dd942020-07-21 15:33:31 -07001903 log.debug("Queue netcfg {}", event);
Charles Chan39b75522018-04-21 00:44:29 -07001904 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001905 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001906 break;
1907 default:
1908 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001909 }
1910 }
Saurav Das261c3002017-06-13 15:35:54 -07001911
Charles Chanc4a68c32018-01-03 16:26:32 -08001912 @Override
1913 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001914 if (event.type() == CONFIG_REGISTERED ||
1915 event.type() == CONFIG_UNREGISTERED) {
1916 log.debug("Ignore event {} due to type mismatch", event);
1917 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001918 }
Saurav Dase321cff2018-02-09 17:26:45 -08001919
1920 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1921 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
Charles Chana01d57c2019-07-19 16:25:38 -07001922 !event.configClass().equals(InterfaceConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001923 log.debug("Ignore event {} due to class mismatch", event);
1924 return false;
1925 }
1926
1927 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001928 }
1929
Saurav Das261c3002017-06-13 15:35:54 -07001930 private final class ConfigChange implements Runnable {
1931 @Override
1932 public void run() {
1933 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001934 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001935 for (Device device : deviceService.getDevices()) {
1936 processDeviceAdded(device);
1937 }
1938 defaultRoutingHandler.startPopulationProcess();
1939 }
1940 }
Charles Chan72f556a2015-10-05 17:50:33 -07001941 }
Charles Chanf4586112015-11-09 16:37:23 -08001942
Charles Chan3f4aca62018-03-21 16:57:47 -07001943 private class InternalLinkListener implements LinkListener {
1944 @Override
1945 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001946 if (mainEventExecutor == null) {
1947 return;
1948 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001949 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1950 event.type() == LinkEvent.Type.LINK_UPDATED ||
1951 event.type() == LinkEvent.Type.LINK_REMOVED) {
1952 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001953 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1954 mainEventExecutor.execute(new InternalEventHandler(event));
1955 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001956 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001957 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001958 }
1959 }
1960 }
1961
1962 private class InternalDeviceListener implements DeviceListener {
1963 @Override
1964 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001965 if (mainEventExecutor == null) {
1966 return;
1967 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001968 switch (event.type()) {
1969 case DEVICE_ADDED:
1970 case PORT_UPDATED:
1971 case PORT_ADDED:
1972 case DEVICE_UPDATED:
1973 case DEVICE_AVAILABILITY_CHANGED:
1974 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001975 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1976 mainEventExecutor.execute(new InternalEventHandler(event));
1977 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001978 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001979 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001980 break;
1981 default:
1982 }
1983 }
1984 }
1985
1986 private class InternalTopologyListener implements TopologyListener {
1987 @Override
1988 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001989 if (mainEventExecutor == null) {
1990 return;
1991 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001992 switch (event.type()) {
1993 case TOPOLOGY_CHANGED:
1994 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001995 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1996 mainEventExecutor.execute(new InternalEventHandler(event));
1997 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001998 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001999 }
Charles Chan3f4aca62018-03-21 16:57:47 -07002000 break;
2001 default:
2002 }
2003 }
2004 }
2005
Charles Chanf4586112015-11-09 16:37:23 -08002006 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08002007 @Override
2008 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002009 if (hostEventExecutor == null) {
2010 return;
2011 }
Charles Chanf4586112015-11-09 16:37:23 -08002012 switch (event.type()) {
2013 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08002014 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08002015 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08002016 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07002017 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07002018 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08002019 break;
2020 default:
2021 log.warn("Unsupported host event type: {}", event.type());
2022 break;
2023 }
2024 }
2025 }
2026
Charles Chanc91c8782016-03-30 17:54:24 -07002027 private class InternalMcastListener implements McastListener {
2028 @Override
2029 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002030 if (mcastEventExecutor == null) {
2031 return;
2032 }
Charles Chanc91c8782016-03-30 17:54:24 -07002033 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07002034 case SOURCES_ADDED:
2035 case SOURCES_REMOVED:
2036 case SINKS_ADDED:
2037 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07002038 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02002039 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07002040 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07002041 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01002042 break;
Charles Chanc91c8782016-03-30 17:54:24 -07002043 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07002044 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07002045 break;
2046 }
2047 }
2048 }
Charles Chan41f5ec02016-06-13 18:54:31 -07002049
Charles Chandebfea32016-10-24 14:52:01 -07002050 private class InternalRouteEventListener implements RouteListener {
2051 @Override
2052 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002053 if (routeEventExecutor == null) {
2054 return;
2055 }
Charles Chandebfea32016-10-24 14:52:01 -07002056 switch (event.type()) {
2057 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07002058 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07002059 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07002060 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07002061 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07002062 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07002063 break;
Charles Chandebfea32016-10-24 14:52:01 -07002064 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07002065 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07002066 break;
2067 }
2068 }
2069 }
Saurav Das62ae6792017-05-15 15:34:25 -07002070
Charles Chanfbcb8812018-04-18 18:41:05 -07002071 private class InternalMastershipListener implements MastershipListener {
2072 @Override
2073 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07002074 if (mainEventExecutor == null) {
2075 return;
2076 }
Charles Chanfbcb8812018-04-18 18:41:05 -07002077 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07002078 case MASTER_CHANGED:
2079 log.debug("Mastership event: {}/{}", event.subject(),
2080 event.roleInfo());
2081 mainEventExecutor.execute(new InternalEventHandler(event));
2082 break;
2083 case BACKUPS_CHANGED:
2084 case SUSPENDED:
2085 default:
2086 log.debug("Mastership event type {} not handled", event.type());
2087 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07002088 }
2089 }
2090 }
2091
Saurav Das00e553b2018-04-21 17:19:48 -07002092 class InternalClusterListener implements ClusterEventListener {
2093 private Instant lastClusterEvent = Instant.EPOCH;
2094
2095 long timeSinceLastClusterEvent() {
2096 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
2097 }
2098
2099 @Override
2100 public void event(ClusterEvent event) {
2101 switch (event.type()) {
2102 case INSTANCE_ACTIVATED:
2103 case INSTANCE_ADDED:
2104 case INSTANCE_READY:
2105 log.debug("Cluster event {} ignored", event.type());
2106 break;
2107 case INSTANCE_DEACTIVATED:
2108 case INSTANCE_REMOVED:
2109 log.info("** Cluster event {}", event.type());
2110 lastClusterEvent = Instant.now();
2111 break;
2112 default:
2113 break;
2114 }
2115
2116 }
2117
2118 }
2119
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002120 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
2121 try {
2122 Set<Interface> intfs = conf.getInterfaces();
2123 Set<Interface> prevIntfs = prevConf.getInterfaces();
2124
2125 // Now we only handle one interface config at each port.
2126 if (intfs.size() != 1 || prevIntfs.size() != 1) {
2127 log.warn("Interface update aborted - one at a time is allowed, " +
2128 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
2129 return;
2130 }
2131
Andrea Campanella060cad82018-04-17 12:09:34 +02002132 //The system is in an incoherent state, abort
2133 if (defaultRoutingHandler == null) {
2134 log.warn("Interface update aborted, defaultRoutingHandler is null");
2135 return;
2136 }
2137
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002138 Interface intf = intfs.stream().findFirst().get();
2139 Interface prevIntf = prevIntfs.stream().findFirst().get();
2140
2141 DeviceId deviceId = intf.connectPoint().deviceId();
2142 PortNumber portNum = intf.connectPoint().port();
pierventrea3989be2021-01-08 16:43:17 +01002143 // We need to do nexthop update al least one time for each
2144 // interface config change. There is no difference when it is done;
2145 boolean updateNexthop = false;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002146
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002147 removeSubnetConfig(prevIntf.connectPoint(),
2148 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
2149 new HashSet<>(intf.ipAddressesList())));
2150
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002151 if (!prevIntf.vlanNative().equals(VlanId.NONE)
2152 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
2153 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
2154 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
2155 // Update filtering objective and L2IG group bucket
2156 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
2157 } else {
pierventrea3989be2021-01-08 16:43:17 +01002158 // RemoveVlanNative - affected scenarios:
2159 // (T,N)->U; (T*,N)->U; (T,N)->(T,N); (T,N)->T
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002160 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
pierventrea3989be2021-01-08 16:43:17 +01002161 // Update the nexthops of the indirect routes
2162 updateNexthop = true;
2163 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002164 }
2165 }
2166
2167 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
2168 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2169 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2170 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002171 // Update filtering objective and L2IG group bucket - affected scenarios:
2172 // U->(T*,N); U->T*
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002173 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
pierventrea3989be2021-01-08 16:43:17 +01002174 if (!updateNexthop) {
2175 updateNexthop = true;
2176 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2177 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002178 } else {
pierventrea3989be2021-01-08 16:43:17 +01002179 // RemoveVlanUntagged - affected scenarios:
2180 // U->U; U->(T,N); U->T
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002181 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
pierventrea3989be2021-01-08 16:43:17 +01002182 if (!updateNexthop) {
2183 updateNexthop = true;
2184 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2185 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002186 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002187 }
2188
2189 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002190 // RemoveVlanTagged - affected scenarios:
2191 // T->U; T->T; (T,N*)->U; (T,N)->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002192 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2193 .filter(i -> !intf.vlanUntagged().equals(i))
2194 .filter(i -> !intf.vlanNative().equals(i))
2195 .forEach(vlanId -> updateVlanConfigInternal(
2196 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002197 }
2198
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002199 if (!intf.vlanNative().equals(VlanId.NONE)
2200 && !prevIntf.vlanNative().equals(intf.vlanNative())
2201 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2202 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2203 // Update filtering objective and L2IG group bucket
2204 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2205 } else {
pierventrea3989be2021-01-08 16:43:17 +01002206 // AddVlanNative - affected scenarios
2207 // U->(T,N); U->(T*,N); T->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002208 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
pierventrea3989be2021-01-08 16:43:17 +01002209 if (!updateNexthop) {
2210 updateNexthop = true;
2211 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2212 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002213 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002214 }
2215
2216 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002217 // AddVlanTagged - affected scenarios
2218 // U->T; U->(T,N*); T->T; (T,N)->(T,N)
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002219 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2220 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2221 .filter(i -> !prevIntf.vlanNative().equals(i))
2222 .forEach(vlanId -> updateVlanConfigInternal(
2223 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002224 );
pierventrea3989be2021-01-08 16:43:17 +01002225
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002226 }
2227
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002228 if (!intf.vlanUntagged().equals(VlanId.NONE)
2229 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2230 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2231 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
pierventrea3989be2021-01-08 16:43:17 +01002232 // Update filtering objective and L2IG group bucket - affected scenarios
2233 // (T*,N)->U; T*->U
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002234 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
pierventrea3989be2021-01-08 16:43:17 +01002235 if (!updateNexthop) {
2236 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2237 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002238 } else {
pierventrea3989be2021-01-08 16:43:17 +01002239 // AddVlanUntagged - affected scenarios
2240 // U->U; (T,N)->U; T->U
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002241 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
pierventrea3989be2021-01-08 16:43:17 +01002242 if (!updateNexthop) {
2243 routeEventExecutor.execute(() -> routeHandler.processIntfVlanUpdatedEvent(deviceId, portNum));
2244 }
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002245 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002246 }
2247 addSubnetConfig(prevIntf.connectPoint(),
2248 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2249 new HashSet<>(prevIntf.ipAddressesList())));
2250 } catch (ConfigException e) {
2251 log.error("Error in configuration");
2252 }
2253 }
2254
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002255 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2256 VlanId vlanId, boolean pushVlan) {
2257 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2258 if (grpHandler == null) {
2259 log.warn("Failed to retrieve group handler for device {}", deviceId);
2260 return;
2261 }
2262
2263 // Update filtering objective for a single port
2264 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2265 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2266
2267 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2268 // Update L2IG bucket of the port
2269 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2270 } else {
2271 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2272 }
2273 }
2274
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002275 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2276 VlanId vlanId, boolean pushVlan, boolean install) {
2277 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2278 if (grpHandler == null) {
2279 log.warn("Failed to retrieve group handler for device {}", deviceId);
2280 return;
2281 }
2282
2283 // Update filtering objective for a single port
2284 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2285
2286 // Update filtering objective for multicast ingress port
2287 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2288
2289 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2290
2291 if (nextId != -1 && !install) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002292 // Remove L2 Bridging rule and L3 Unicast rule to the host
pierventrea3989be2021-01-08 16:43:17 +01002293 ScheduledFuture<?> future = hostEventExecutor.schedule(
2294 () -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install),
2295 0, TimeUnit.SECONDS);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002296 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2297 // only if there is no port configured on that VLAN ID
2298 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2299 // Remove broadcast forwarding rule for the VLAN
2300 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2301 // Remove L2FG for VLAN
2302 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2303 } else {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002304 // Remove a single port from L2FG
2305 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002306 }
pierventrea3989be2021-01-08 16:43:17 +01002307 // Before moving forward we have to be sure that processIntfVlanUpdatedEvent completed;
2308 try {
2309 future.get();
2310 } catch (InterruptedException | ExecutionException e) {
2311 log.warn("Exception caught when executing updateVlanConfigInternal future");
2312 }
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002313 // Remove L2IG of the port
2314 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002315 } else if (install) {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002316 // Create L2IG of the port
2317 grpHandler.createPortNextObjective(deviceId, portNum, vlanId, pushVlan);
2318 // Create L2 Bridging rule and L3 Unicast rule to the host
2319 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2320 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002321 if (nextId != -1) {
2322 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002323 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002324 } else {
2325 // Create L2FG for VLAN
2326 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2327 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2328 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002329 } else {
2330 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2331 }
2332 }
2333
2334 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2335 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2336 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2337
2338 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2339 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2340 .filter(intf -> !intf.connectPoint().equals(cp))
2341 .flatMap(intf -> intf.ipAddressesList().stream())
2342 .collect(Collectors.toSet());
2343 // 1. Partial subnet population
2344 // Remove routing rules for removed subnet from previous configuration,
2345 // which does not also exist in other interfaces in the same device
2346 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2347 .map(InterfaceIpAddress::subnetAddress)
2348 .collect(Collectors.toSet());
2349
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002350 Set<IpPrefix> subnetsToBeRevoked = ipPrefixSet.stream()
2351 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2352 .collect(Collectors.toSet());
2353
2354 // Check if any of the subnets to be revoked is configured in the pairDevice.
2355 // If any, repopulate the subnet with pairDevice connectPoint instead of revoking.
2356 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2357 if (pairDevice.isPresent()) {
2358 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2359
2360 Set<IpPrefix> subnetsExistingInPairDevice = subnetsToBeRevoked.stream()
2361 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2362 .collect(Collectors.toSet());
2363
2364 // Update the subnets existing in pair device with pair device connect point.
2365 if (!subnetsExistingInPairDevice.isEmpty()) {
2366 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2367 ConnectPoint pairDeviceCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2368 log.debug("Updating the subnets: {} with pairDevice connectPoint as it exists in the Pair device: {}",
2369 subnetsExistingInPairDevice, pairDeviceCp);
2370 defaultRoutingHandler.populateSubnet(Collections.singleton(pairDeviceCp), subnetsExistingInPairDevice);
2371 }
2372
2373 // Remove only the subnets that are not configured in the pairDevice.
2374 subnetsToBeRevoked = Sets.difference(subnetsToBeRevoked, subnetsExistingInPairDevice);
2375 }
2376
2377 if (!subnetsToBeRevoked.isEmpty()) {
2378 log.debug("Removing subnets for connectPoint: {}, subnets: {}", cp, subnetsToBeRevoked);
2379 defaultRoutingHandler.revokeSubnet(subnetsToBeRevoked);
2380 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002381
2382 // 2. Interface IP punts
2383 // Remove IP punts for old Intf address
2384 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2385 .map(InterfaceIpAddress::ipAddress)
2386 .collect(Collectors.toSet());
2387 ipAddressSet.stream()
2388 .map(InterfaceIpAddress::ipAddress)
2389 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2390 .forEach(interfaceIpAddress ->
2391 routingRulePopulator.revokeSingleIpPunts(
2392 cp.deviceId(), interfaceIpAddress));
2393
2394 // 3. Host unicast routing rule
2395 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002396 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002397 }
2398
2399 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2400 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2401 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2402
2403 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2404 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2405 .filter(intf -> !intf.connectPoint().equals(cp))
2406 .flatMap(intf -> intf.ipAddressesList().stream())
2407 .collect(Collectors.toSet());
2408 // 1. Partial subnet population
2409 // Add routing rules for newly added subnet, which does not also exist in
2410 // other interfaces in the same device
2411 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2412 .map(InterfaceIpAddress::subnetAddress)
2413 .collect(Collectors.toSet());
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002414 Set<IpPrefix> subnetsToBePopulated = ipPrefixSet.stream()
2415 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2416 .collect(Collectors.toSet());
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002417
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002418 if (!subnetsToBePopulated.isEmpty()) {
2419 log.debug("Adding subnets for connectPoint: {}, subnets: {}", cp, subnetsToBePopulated);
2420
2421 // check if pair-device has the same subnet configured?
2422 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2423 if (pairDevice.isPresent()) {
2424 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2425
2426 Set<IpPrefix> subnetsToBePopulatedAsDualHomed = subnetsToBePopulated.stream()
2427 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2428 .collect(Collectors.toSet());
2429 Set<IpPrefix> subnetsToBePopulatedAsSingleHomed = Sets.difference(subnetsToBePopulated,
2430 subnetsToBePopulatedAsDualHomed);
2431
2432 if (!subnetsToBePopulatedAsSingleHomed.isEmpty()) {
2433 defaultRoutingHandler.populateSubnet(
2434 Collections.singleton(cp),
2435 subnetsToBePopulatedAsSingleHomed);
2436 }
2437
2438 if (!subnetsToBePopulatedAsDualHomed.isEmpty()) {
2439 Set<ConnectPoint> cpts = new HashSet<>();
2440 cpts.add(cp);
2441 // As Subnets is DualHomed adding the pairDevice also as ConnectPoint.
2442 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2443 ConnectPoint pairCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2444 cpts.add(pairCp);
2445
2446 log.debug("Adding DualHomed subnets for connectPoint: {} and its pair device: {}, subnets: {}",
2447 cp, pairCp, subnetsToBePopulatedAsDualHomed);
2448
2449 // populating the subnets as DualHomed
2450 defaultRoutingHandler.populateSubnet(
2451 cpts,
2452 subnetsToBePopulated);
2453
2454 // revoking the subnets populated in the device as it is now Dualhomed.
2455 defaultRoutingHandler.revokeSubnet(Collections.singleton(cp.deviceId()),
2456 subnetsToBePopulatedAsDualHomed);
2457 }
2458 } else {
2459 defaultRoutingHandler.populateSubnet(
2460 Collections.singleton(cp),
2461 subnetsToBePopulated);
2462 }
2463 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002464
2465 // 2. Interface IP punts
2466 // Add IP punts for new Intf address
2467 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2468 .map(InterfaceIpAddress::ipAddress)
2469 .collect(Collectors.toSet());
2470 ipAddressSet.stream()
2471 .map(InterfaceIpAddress::ipAddress)
2472 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2473 .forEach(interfaceIpAddress ->
2474 routingRulePopulator.populateSingleIpPunts(
2475 cp.deviceId(), interfaceIpAddress));
2476
2477 // 3. Host unicast routing rule
2478 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002479 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002480 }
sangho80f11cb2015-04-01 13:05:26 -07002481}