blob: a948bfde72627941e4c1fd4caa72aafd598a0f70 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart61e24e12017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chanf0ae41e2017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070023import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080024import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070025import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080026import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070027import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070028import org.onlab.packet.IpPrefix;
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +000029import org.onlab.packet.MacAddress;
Carmelo Cascone61004262020-01-16 13:36:02 -080030import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070031import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080032import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070033import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070034import org.onosproject.cluster.ClusterEvent;
35import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010036import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070037import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020038import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070039import org.onosproject.core.ApplicationId;
40import org.onosproject.core.CoreService;
41import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070042import org.onosproject.mastership.MastershipEvent;
43import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070044import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070045import org.onosproject.mcast.api.McastEvent;
46import org.onosproject.mcast.api.McastListener;
47import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080048import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070049import org.onosproject.net.Device;
50import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070051import org.onosproject.net.Host;
52import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070053import org.onosproject.net.Link;
54import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080055import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070056import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070057import org.onosproject.net.config.ConfigFactory;
58import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070059import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070060import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070061import org.onosproject.net.config.basics.InterfaceConfig;
62import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070063import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080064import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070065import org.onosproject.net.device.DeviceEvent;
66import org.onosproject.net.device.DeviceListener;
67import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080068import org.onosproject.net.flow.TrafficSelector;
69import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070070import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070071import org.onosproject.net.flowobjective.NextObjective;
Charles Chanf4586112015-11-09 16:37:23 -080072import org.onosproject.net.host.HostEvent;
73import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070074import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080075import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070076import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020077import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070078import org.onosproject.net.intf.Interface;
79import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080080import org.onosproject.net.link.LinkEvent;
81import org.onosproject.net.link.LinkListener;
82import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
96import org.onosproject.segmentrouting.config.DeviceConfiguration;
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;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800109import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700110import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800111import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700112import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700113import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800114import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Saurav Das261c3002017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Carmelo Cascone61004262020-01-16 13:36:02 -0800116import org.onosproject.segmentrouting.storekey.MacVlanNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700120import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700121import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700122import org.onosproject.store.service.EventuallyConsistentMap;
123import org.onosproject.store.service.EventuallyConsistentMapBuilder;
124import org.onosproject.store.service.StorageService;
125import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800126import org.osgi.service.component.ComponentContext;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700127import org.osgi.service.component.annotations.Activate;
128import org.osgi.service.component.annotations.Component;
129import org.osgi.service.component.annotations.Deactivate;
130import org.osgi.service.component.annotations.Modified;
131import org.osgi.service.component.annotations.Reference;
132import org.osgi.service.component.annotations.ReferenceCardinality;
Charles Chanb4f9cd12019-02-27 11:46:32 -0800133import org.osgi.service.component.annotations.ReferencePolicy;
sangho80f11cb2015-04-01 13:05:26 -0700134import org.slf4j.Logger;
135import org.slf4j.LoggerFactory;
136
Saurav Das00e553b2018-04-21 17:19:48 -0700137import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700138import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800139import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800140import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800141import java.util.HashSet;
142import java.util.List;
143import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800144import java.util.Optional;
145import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200146import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800147import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200148import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan77cdde42018-05-08 21:35:50 -0700149import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800150import java.util.concurrent.Executors;
151import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800152import java.util.concurrent.TimeUnit;
153import java.util.concurrent.atomic.AtomicBoolean;
154import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700155
Charles Chand6d25332016-02-26 22:19:52 -0800156import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800157import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700158import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800159import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
160import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700161import static org.onosproject.segmentrouting.OsgiPropertyConstants.ACTIVE_PROBING_DEFAULT;
162import static org.onosproject.segmentrouting.OsgiPropertyConstants.DEFAULT_INTERNAL_VLAN_DEFAULT;
163import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ACTIVE_PROBING;
164import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_DEFAULT_INTERNAL_VLAN;
165import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_PW_TRANSPORT_VLAN;
166import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_RESPOND_TO_UNKNOWN_HOSTS;
167import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_DOUBLE_TAGGED_HOSTS;
psneha86e60d32019-03-26 06:31:41 -0400168import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_ROUTE_SIMPLIFICATION;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700169import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SINGLE_HOMED_DOWN;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700170import static org.onosproject.segmentrouting.OsgiPropertyConstants.PROP_SYMMETRIC_PROBING;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700171import static org.onosproject.segmentrouting.OsgiPropertyConstants.PW_TRANSPORT_VLAN_DEFAULT;
172import static org.onosproject.segmentrouting.OsgiPropertyConstants.RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
173import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
psneha86e60d32019-03-26 06:31:41 -0400174import static org.onosproject.segmentrouting.OsgiPropertyConstants.ROUTE_SIMPLIFICATION_DEFAULT;
Ray Milkey05edbfc2018-10-23 14:23:16 -0700175import static org.onosproject.segmentrouting.OsgiPropertyConstants.SINGLE_HOMED_DOWN_DEFAULT;
Ray Milkeye96d0de2018-11-02 17:12:21 -0700176import static org.onosproject.segmentrouting.OsgiPropertyConstants.SYMMETRIC_PROBING_DEFAULT;
Charles Chand6d25332016-02-26 22:19:52 -0800177
Charles Chanb7f75ac2016-01-11 18:28:54 -0800178/**
179 * Segment routing manager.
180 */
Ray Milkey05edbfc2018-10-23 14:23:16 -0700181@Component(
182 immediate = true,
183 service = SegmentRoutingService.class,
184 property = {
185 PROP_ACTIVE_PROBING + ":Boolean=" + ACTIVE_PROBING_DEFAULT,
186 PROP_SINGLE_HOMED_DOWN + ":Boolean=" + SINGLE_HOMED_DOWN_DEFAULT,
187 PROP_RESPOND_TO_UNKNOWN_HOSTS + ":Boolean=" + RESPOND_TO_UNKNOWN_HOSTS_DEFAULT,
188 PROP_ROUTE_DOUBLE_TAGGED_HOSTS + ":Boolean=" + ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT,
189 PROP_DEFAULT_INTERNAL_VLAN + ":Integer=" + DEFAULT_INTERNAL_VLAN_DEFAULT,
190 PROP_PW_TRANSPORT_VLAN + ":Integer=" + PW_TRANSPORT_VLAN_DEFAULT,
psneha86e60d32019-03-26 06:31:41 -0400191 PROP_SYMMETRIC_PROBING + ":Boolean=" + SYMMETRIC_PROBING_DEFAULT,
192 PROP_ROUTE_SIMPLIFICATION + ":Boolean=" + ROUTE_SIMPLIFICATION_DEFAULT
Ray Milkey05edbfc2018-10-23 14:23:16 -0700193 }
194)
sangho27462c62015-05-14 00:39:53 -0700195public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700196
Charles Chan46fdfaf2016-11-09 20:51:44 -0800197 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700198 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700199
Ray Milkey2bd24a92018-08-17 14:54:17 -0700200 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700201 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700202
Ray Milkey2bd24a92018-08-17 14:54:17 -0700203 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chancf789822019-03-22 10:04:27 -0700204 public NeighbourResolutionService neighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800205
Ray Milkey2bd24a92018-08-17 14:54:17 -0700206 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100207 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700208
Ray Milkey2bd24a92018-08-17 14:54:17 -0700209 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700210 PacketService packetService;
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 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700214
Ray Milkey2bd24a92018-08-17 14:54:17 -0700215 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700216 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800217
Ray Milkey2bd24a92018-08-17 14:54:17 -0700218 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100219 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700220
Ray Milkey2bd24a92018-08-17 14:54:17 -0700221 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800222 DeviceAdminService deviceAdminService;
223
Ray Milkey2bd24a92018-08-17 14:54:17 -0700224 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800225 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700226
Ray Milkey2bd24a92018-08-17 14:54:17 -0700227 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100228 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700229
Ray Milkey2bd24a92018-08-17 14:54:17 -0700230 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800231 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700232
Ray Milkey2bd24a92018-08-17 14:54:17 -0700233 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800234 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700235
Ray Milkey2bd24a92018-08-17 14:54:17 -0700236 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100237 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700238
Ray Milkey2bd24a92018-08-17 14:54:17 -0700239 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan83163812018-01-09 13:45:07 -0800240 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700241
Ray Milkey2bd24a92018-08-17 14:54:17 -0700242 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan19b70032019-04-17 14:20:26 -0700243 public RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800244
Ray Milkey2bd24a92018-08-17 14:54:17 -0700245 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800246 public NetworkConfigRegistry cfgService;
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 InterfaceService interfaceService;
250
Ray Milkey2bd24a92018-08-17 14:54:17 -0700251 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi580fd8a2018-01-16 10:47:50 +0100252 public ClusterService clusterService;
253
Ray Milkey2bd24a92018-08-17 14:54:17 -0700254 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pierdb27b8d2018-04-17 16:29:56 +0200255 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100256
Ray Milkey2bd24a92018-08-17 14:54:17 -0700257 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700258 public LeadershipService leadershipService;
259
Charles Chanb4f9cd12019-02-27 11:46:32 -0800260 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
Charles Chanb4f9cd12019-02-27 11:46:32 -0800261 policy = ReferencePolicy.DYNAMIC)
Carmelo Cascone61004262020-01-16 13:36:02 -0800262 public volatile XconnectService xconnectService;
Charles Chan8d316332018-06-19 20:31:57 -0700263
Ray Milkey05edbfc2018-10-23 14:23:16 -0700264 /** Enable active probing to discover dual-homed hosts. */
265 boolean activeProbing = ACTIVE_PROBING_DEFAULT;
Charles Chan873661e2017-11-30 15:37:50 -0800266
Ray Milkeye96d0de2018-11-02 17:12:21 -0700267 /** Enable only send probe on the same port number of the pair device. */
268 boolean symmetricProbing = SYMMETRIC_PROBING_DEFAULT;
Mayank Tiwarif7942402018-10-29 18:27:35 -0400269
Ray Milkey05edbfc2018-10-23 14:23:16 -0700270 /** Enable administratively taking down single-homed hosts. */
271 boolean singleHomedDown = SINGLE_HOMED_DOWN_DEFAULT;
Saurav Dasec683dc2018-04-27 18:42:30 -0700272
Ray Milkey05edbfc2018-10-23 14:23:16 -0700273 /** Enable this to respond to ARP/NDP requests from unknown hosts. */
274 boolean respondToUnknownHosts = RESPOND_TO_UNKNOWN_HOSTS_DEFAULT;
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700275
Ray Milkey05edbfc2018-10-23 14:23:16 -0700276 /** Program flows and groups to pop and route double tagged hosts. */
277 boolean routeDoubleTaggedHosts = ROUTE_DOUBLE_TAGGED_HOSTS_DEFAULT;
Charles Chan4eb73bb2018-07-19 14:55:31 -0700278
Ray Milkey05edbfc2018-10-23 14:23:16 -0700279 /** internal vlan assigned by default to unconfigured ports. */
280 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700281
Ray Milkey05edbfc2018-10-23 14:23:16 -0700282 /** vlan used for transport of pseudowires between switches. */
283 private int pwTransportVlan = PW_TRANSPORT_VLAN_DEFAULT;
Saurav Das9bf49582018-08-13 15:34:26 -0700284
psneha86e60d32019-03-26 06:31:41 -0400285 /** Enabling route simplification. */
286 boolean routeSimplification = ROUTE_SIMPLIFICATION_DEFAULT;
287
Charles Chandebfea32016-10-24 14:52:01 -0700288 ArpHandler arpHandler = null;
289 IcmpHandler icmpHandler = null;
290 IpHandler ipHandler = null;
291 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700292 ApplicationId appId;
293 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700294
Charles Chandebfea32016-10-24 14:52:01 -0700295 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700296 private TunnelHandler tunnelHandler = null;
297 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700298 private InternalPacketProcessor processor = null;
299 private InternalLinkListener linkListener = null;
300 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700301 private AppConfigHandler appCfgHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800302 McastHandler mcastHandler = null;
303 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800304 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800305 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800306 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800307 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100308 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800309 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700310 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
311 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700312 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100313 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700314 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700315 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200316 //Completable future for network configuration process to buffer config events handling during activation
317 private CompletableFuture<Boolean> networkConfigCompletion = null;
Ray Milkey521e4392018-11-16 15:15:14 -0800318 private final Object networkConfigCompletionLock = new Object();
Charles Chan39b75522018-04-21 00:44:29 -0700319 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700320
Charles Chan52003922018-04-05 16:31:15 -0700321 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700322 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700323
Charles Chanfbcb8812018-04-18 18:41:05 -0700324 // Handles host, route and mcast events respectively
325 private ScheduledExecutorService hostEventExecutor;
326 private ScheduledExecutorService routeEventExecutor;
327 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700328 private ExecutorService packetExecutor;
Charles Chana7601c92019-01-23 15:03:17 -0800329 ExecutorService neighborExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700330
331 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800332 /**
Saurav Das261c3002017-06-13 15:35:54 -0700333 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700334 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800335 */
Charles Chan873661e2017-11-30 15:37:50 -0800336 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700337 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800338 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700339 * Per device next objective ID store with (device id + vlanid) as key.
340 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800341 */
Charles Chan873661e2017-11-30 15:37:50 -0800342 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800343 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800344 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700345 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000346 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800347 */
Charles Chan873661e2017-11-30 15:37:50 -0800348 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800349 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800350
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700351 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000352 * Per device next objective ID store with (device id + MAC address + vlan) as key.
353 * Used to keep track of L3 unicast group for indirect hosts.
354 */
355 private EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer>
356 macVlanNextObjStore = null;
357
Saurav Das2d94d312015-11-24 23:21:05 -0800358 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
359 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700360
Saurav Das261c3002017-06-13 15:35:54 -0700361 private AtomicBoolean programmingScheduled = new AtomicBoolean();
362
Charles Chanc91c8782016-03-30 17:54:24 -0700363 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700364 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
365 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700366 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700367 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800368 public SegmentRoutingDeviceConfig createConfig() {
369 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700370 }
371 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800372
Charles Chanc91c8782016-03-30 17:54:24 -0700373 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700374 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
375 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700376 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800377 @Override
378 public SegmentRoutingAppConfig createConfig() {
379 return new SegmentRoutingAppConfig();
380 }
381 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800382
Charles Chanc91c8782016-03-30 17:54:24 -0700383 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700384 new ConfigFactory<ApplicationId, McastConfig>(
385 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700386 McastConfig.class, "multicast") {
387 @Override
388 public McastConfig createConfig() {
389 return new McastConfig();
390 }
391 };
392
Charles Chan1963f4f2016-02-18 14:22:42 -0800393 /**
394 * Segment Routing App ID.
395 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800396 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das7c305372015-10-28 12:39:42 -0700397
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700398 /**
399 * Minumum and maximum value of dummy VLAN ID to be allocated.
400 */
401 public static final int MIN_DUMMY_VLAN_ID = 2;
402 public static final int MAX_DUMMY_VLAN_ID = 4093;
403
Charles Chana7601c92019-01-23 15:03:17 -0800404 private static final int DEFAULT_POOL_SIZE = 32;
405
Saurav Dasec683dc2018-04-27 18:42:30 -0700406 Instant lastEdgePortEvent = Instant.EPOCH;
407
sangho80f11cb2015-04-01 13:05:26 -0700408 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800409 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800410 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700411
Charles Chana7601c92019-01-23 15:03:17 -0800412 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(
413 groupedThreads("onos/sr", "event-main-%d", log));
414 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(
415 groupedThreads("onos/sr", "event-host-%d", log));
416 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(
417 groupedThreads("onos/sr", "event-route-%d", log));
418 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(
419 groupedThreads("onos/sr", "event-mcast-%d", log));
420 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("onos/sr", "packet-%d", log));
421 neighborExecutor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE,
422 groupedThreads("onos/sr", "neighbor-%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700423
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700424 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700425 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700426 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700427 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700428 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700429 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700430 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700431 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700432 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700433
Charles Chan10b0fb72017-02-02 16:20:42 -0800434 log.debug("Creating EC map vlannextobjectivestore");
435 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
436 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
437 vlanNextObjStore = vlanNextObjMapBuilder
438 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700439 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700440 .withTimestampProvider((k, v) -> new WallClockTimestamp())
441 .build();
442
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000443 log.debug("Creating EC map macvlannextobjectivestore");
444 EventuallyConsistentMapBuilder<MacVlanNextObjectiveStoreKey, Integer>
445 macVlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
446 macVlanNextObjStore = macVlanNextObjMapBuilder
447 .withName("macvlannextobjectivestore")
448 .withSerializer(createSerializer())
449 .withTimestampProvider((k, v) -> new WallClockTimestamp())
450 .build();
451
Saurav Das2d94d312015-11-24 23:21:05 -0800452 log.debug("Creating EC map subnetnextobjectivestore");
453 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
454 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
455 portNextObjStore = portNextObjMapBuilder
456 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700457 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800458 .withTimestampProvider((k, v) -> new WallClockTimestamp())
459 .build();
460
sangho4a5c42a2015-05-20 22:16:38 -0700461 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
462 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700463 tunnelStore = tunnelMapBuilder
464 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700465 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700466 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700467 .build();
468
469 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
470 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700471 policyStore = policyMapBuilder
472 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700473 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700474 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700475 .build();
476
Charles Chan97979802020-02-26 15:04:44 -0800477 processor = new InternalPacketProcessor();
478 linkListener = new InternalLinkListener();
479 deviceListener = new InternalDeviceListener();
480 appCfgHandler = new AppConfigHandler(this);
481 mcastHandler = new McastHandler(this);
482 hostHandler = new HostHandler(this);
483 linkHandler = new LinkHandler(this);
484 routeHandler = new RouteHandler(this);
485 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
486 l2TunnelHandler = new DefaultL2TunnelHandler(this);
487 topologyHandler = new TopologyHandler(this);
488
Saurav Dasc3604f12016-03-23 11:22:49 -0700489 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700490 "purgeOnDisconnection", "true", false);
Saurav Dasc3604f12016-03-23 11:22:49 -0700491 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700492 "purgeOnDisconnection", "true", false);
Pier Luigib9632ba2017-01-12 18:14:58 -0800493 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700494 "requestInterceptsEnabled", "false", false);
Charles Chanc1909e12017-08-08 15:13:37 -0700495 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700496 "requestInterceptsEnabled", "false", false);
Charles Chan9597f8d2017-07-24 15:56:10 -0700497 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700498 "arpEnabled", "false", false);
Pier Luigi0ebeb312017-02-02 22:31:34 -0800499 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700500 "greedyLearningIpv6", "true", false);
Charles Chancf8ea472017-02-28 15:15:17 -0800501 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700502 "forceUnprovision", "true", false);
Charles Chanc7b73c72017-08-10 16:57:28 -0700503 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan0fa51db2019-04-10 17:12:20 -0700504 "distributed", "true", false);
Charles Chan804772f2017-08-14 11:42:11 -0700505 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700506 "multihomingEnabled", "true", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800507 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
Charles Chan0fa51db2019-04-10 17:12:20 -0700508 "staleLinkAge", "15000", false);
Charles Chan0c9c19f2017-11-29 19:54:20 -0800509 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700510 "allowDuplicateIps", "false", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800511 // For P4 switches
512 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700513 "fallbackFlowPollFrequency", "4", false);
Yi Tsenga7da8d82018-08-19 03:09:54 +0800514 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan0fa51db2019-04-10 17:12:20 -0700515 "fallbackGroupPollFrequency", "3", false);
Charles Chan873661e2017-11-30 15:37:50 -0800516 compCfgService.registerProperties(getClass());
517 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700518
Charles Chand6d25332016-02-26 22:19:52 -0800519 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700520 cfgService.registerConfigFactory(deviceConfigFactory);
521 cfgService.registerConfigFactory(appConfigFactory);
522 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800523 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200524
Charles Chan6961f222018-01-04 14:26:07 -0800525 cfgListener.configureNetwork();
526
Charles Chan82ab1932016-01-30 23:22:37 -0800527 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700528 packetService.addProcessor(processor, PacketProcessor.director(2));
529 linkService.addListener(linkListener);
530 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700531 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700532 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100533 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700534 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700535 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700536
Charles Chanc12c3d02018-03-09 15:53:44 -0800537 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800538 l2TunnelHandler.init();
539
Ray Milkey521e4392018-11-16 15:15:14 -0800540 synchronized (networkConfigCompletionLock) {
541 networkConfigCompletion.whenComplete((value, ex) -> {
542 //setting to null for easier fall through
543 networkConfigCompletion = null;
544 //process all queued events
545 queuedEvents.forEach(event -> {
546 mainEventExecutor.execute(new InternalEventHandler(event));
547 });
Andrea Campanella060cad82018-04-17 12:09:34 +0200548 });
Ray Milkey521e4392018-11-16 15:15:14 -0800549 }
Andrea Campanella060cad82018-04-17 12:09:34 +0200550
sangho80f11cb2015-04-01 13:05:26 -0700551 log.info("Started");
552 }
553
Saurav Dase6c448a2018-01-18 12:07:33 -0800554 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700555 return new KryoNamespace.Builder()
556 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700557 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800558 VlanNextObjectiveStoreKey.class,
559 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700560 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800561 NextNeighbors.class,
562 Tunnel.class,
563 DefaultTunnel.class,
564 Policy.class,
565 TunnelPolicy.class,
566 Policy.Type.class,
567 PortNextObjectiveStoreKey.class,
568 XConnectStoreKey.class,
569 L2Tunnel.class,
570 L2TunnelPolicy.class,
571 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700572 DefaultL2TunnelPolicy.class,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000573 MacVlanNextObjectiveStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700574 );
575 }
576
sangho80f11cb2015-04-01 13:05:26 -0700577 @Deactivate
578 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700579 mainEventExecutor.shutdown();
580 hostEventExecutor.shutdown();
581 routeEventExecutor.shutdown();
582 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700583 packetExecutor.shutdown();
Charles Chana7601c92019-01-23 15:03:17 -0800584 neighborExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700585
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700586 mainEventExecutor = null;
587 hostEventExecutor = null;
588 routeEventExecutor = null;
589 mcastEventExecutor = null;
590 packetExecutor = null;
Charles Chana7601c92019-01-23 15:03:17 -0800591 neighborExecutor = null;
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700592
Charles Chan72f556a2015-10-05 17:50:33 -0700593 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700594 cfgService.unregisterConfigFactory(deviceConfigFactory);
595 cfgService.unregisterConfigFactory(appConfigFactory);
596 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800597 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700598
Charles Chanfd48c222017-06-19 00:43:31 -0700599 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700600 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700601 linkService.removeListener(linkListener);
602 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700603 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700604 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100605 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700606 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700607 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700608
Charles Chan2e71ef32017-02-23 15:44:08 -0800609 neighbourResolutionService.unregisterNeighbourHandlers(appId);
610
sangho80f11cb2015-04-01 13:05:26 -0700611 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700612 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700613 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700614 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700615 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700616 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700617
Saurav Das261c3002017-06-13 15:35:54 -0700618 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800619 vlanNextObjStore.destroy();
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000620 macVlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700621 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700622 tunnelStore.destroy();
623 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100624
625 mcastHandler.terminate();
piercf557922019-05-17 20:47:06 +0200626 hostHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700627 log.info("Stopped");
628 }
629
Charles Chan873661e2017-11-30 15:37:50 -0800630 @Modified
631 private void modified(ComponentContext context) {
632 Dictionary<?, ?> properties = context.getProperties();
633 if (properties == null) {
634 return;
635 }
636
Ray Milkey48d10c02018-10-24 10:04:03 -0700637 String strActiveProbing = Tools.get(properties, PROP_ACTIVE_PROBING);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700638 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800639 if (expectActiveProbing != activeProbing) {
640 activeProbing = expectActiveProbing;
641 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
642 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700643
Ray Milkeye96d0de2018-11-02 17:12:21 -0700644
645 String strSymmetricProbing = Tools.get(properties, PROP_SYMMETRIC_PROBING);
646 boolean expectSymmetricProbing = Boolean.parseBoolean(strSymmetricProbing);
Mayank Tiwarif7942402018-10-29 18:27:35 -0400647 if (expectSymmetricProbing != symmetricProbing) {
648 symmetricProbing = expectSymmetricProbing;
649 log.info("{} symmetric probing", symmetricProbing ? "Enabling" : "Disabling");
650 }
651
Ray Milkey48d10c02018-10-24 10:04:03 -0700652 String strSingleHomedDown = Tools.get(properties, PROP_SINGLE_HOMED_DOWN);
Saurav Dasec683dc2018-04-27 18:42:30 -0700653 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
654 if (expectSingleHomedDown != singleHomedDown) {
655 singleHomedDown = expectSingleHomedDown;
656 log.info("{} downing of single homed hosts for lost uplinks",
657 singleHomedDown ? "Enabling" : "Disabling");
658 if (singleHomedDown && linkHandler != null) {
659 hostService.getHosts().forEach(host -> host.locations()
660 .forEach(loc -> {
661 if (interfaceService.isConfigured(loc)) {
662 linkHandler.checkUplinksForHost(loc);
663 }
664 }));
665 } else {
666 log.warn("Disabling singleHomedDown does not re-enable already "
667 + "downed ports for single-homed hosts");
668 }
669 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700670
Ray Milkey48d10c02018-10-24 10:04:03 -0700671 String strRespondToUnknownHosts = Tools.get(properties, PROP_RESPOND_TO_UNKNOWN_HOSTS);
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700672 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
673 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
674 respondToUnknownHosts = expectRespondToUnknownHosts;
675 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
676 }
Charles Chan4eb73bb2018-07-19 14:55:31 -0700677
Ray Milkey48d10c02018-10-24 10:04:03 -0700678 String strRouteDoubleTaggedHosts = Tools.get(properties, PROP_ROUTE_DOUBLE_TAGGED_HOSTS);
Charles Chanfbca55e2018-07-24 16:40:35 -0700679 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
680 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
681 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
682 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan4eb73bb2018-07-19 14:55:31 -0700683
Charles Chanfbca55e2018-07-24 16:40:35 -0700684 if (routeDoubleTaggedHosts) {
Charles Chan4eb73bb2018-07-19 14:55:31 -0700685 hostHandler.populateAllDoubleTaggedHost();
686 } else {
687 hostHandler.revokeAllDoubleTaggedHost();
688 }
689 }
Saurav Das9bf49582018-08-13 15:34:26 -0700690
Ray Milkey48d10c02018-10-24 10:04:03 -0700691 String strDefaultInternalVlan = Tools.get(properties, PROP_DEFAULT_INTERNAL_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700692 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
693 if (defIntVlan != defaultInternalVlan) {
694 if (canUseVlanId(defIntVlan)) {
695 log.warn("Default internal vlan value changed from {} to {}.. "
696 + "re-programming filtering rules, but NOT any groups already "
697 + "created with the former value", defaultInternalVlan, defIntVlan);
698 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
699 defaultInternalVlan = defIntVlan;
700 routingRulePopulator
701 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
702 VlanId.vlanId((short) defIntVlan));
703 } else {
704 log.warn("Cannot change default internal vlan to unusable "
705 + "value {}", defIntVlan);
706 }
707 }
708
Ray Milkey48d10c02018-10-24 10:04:03 -0700709 String strPwTxpVlan = Tools.get(properties, PROP_PW_TRANSPORT_VLAN);
Saurav Das9bf49582018-08-13 15:34:26 -0700710 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
711 if (pwTxpVlan != pwTransportVlan) {
712 if (canUseVlanId(pwTxpVlan)) {
713 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
714 + "re-programming filtering rules, but NOT any groups already "
715 + "created with the former value", pwTransportVlan,
716 pwTxpVlan);
717 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
718 pwTransportVlan = pwTxpVlan;
719 routingRulePopulator
720 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
721 VlanId.vlanId((short) pwTxpVlan));
722 } else {
723 log.warn("Cannot change pseudowire transport vlan to unusable "
724 + "value {}", pwTxpVlan);
725 }
726 }
727
psneha86e60d32019-03-26 06:31:41 -0400728 String strRouteSimplification = Tools.get(properties, PROP_ROUTE_SIMPLIFICATION);
729 boolean expectRouteSimplification = Boolean.parseBoolean(strRouteSimplification);
730 if (expectRouteSimplification != routeSimplification) {
731 routeSimplification = expectRouteSimplification;
732 log.info("{} route simplification", routeSimplification ? "Enabling" : "Disabling");
733 }
734
Saurav Das9bf49582018-08-13 15:34:26 -0700735 }
736
737 /**
738 * Returns true if given vlan id is not being used in the system currently,
739 * either as one of the default system wide vlans or as one of the
740 * configured interface vlans.
741 *
742 * @param vlanId given vlan id
743 * @return true if vlan is not currently in use
744 */
745 public boolean canUseVlanId(int vlanId) {
746 if (vlanId >= 4095 || vlanId <= 1) {
747 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
748 vlanId);
749 return false;
750 }
751
752 VlanId vid = VlanId.vlanId((short) vlanId);
753 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
754 log.warn("Vlan id {} value is already in use system-wide. "
755 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
756 getDefaultInternalVlan(), getPwTransportVlan());
757 return false;
758 }
759
760 if (interfaceService.inUse(vid)) {
761 log.warn("Vlan id {} value is already in use on a configured "
762 + "interface in the system", vlanId);
763 return false;
764 }
765 return true;
766 }
767
768 /**
769 * Returns the VlanId assigned internally by default to unconfigured ports.
770 *
771 * @return the default internal vlan id
772 */
773 public VlanId getDefaultInternalVlan() {
774 return VlanId.vlanId((short) defaultInternalVlan);
775 }
776
777 /**
778 * Returns the Vlan id used to transport pseudowire traffic across the
779 * network.
780 *
781 * @return the pseudowire transport vlan id
782 */
783 public VlanId getPwTransportVlan() {
784 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan873661e2017-11-30 15:37:50 -0800785 }
786
sangho27462c62015-05-14 00:39:53 -0700787 @Override
788 public List<Tunnel> getTunnels() {
789 return tunnelHandler.getTunnels();
790 }
791
792 @Override
sanghobd812f82015-06-29 14:58:47 -0700793 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
794 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700795 }
796
797 @Override
sanghobd812f82015-06-29 14:58:47 -0700798 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700799 for (Policy policy: policyHandler.getPolicies()) {
800 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
801 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
802 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
803 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700804 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700805 }
806 }
807 }
sanghobd812f82015-06-29 14:58:47 -0700808 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700809 }
810
811 @Override
sanghobd812f82015-06-29 14:58:47 -0700812 public PolicyHandler.Result removePolicy(Policy policy) {
813 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700814 }
815
816 @Override
sanghobd812f82015-06-29 14:58:47 -0700817 public PolicyHandler.Result createPolicy(Policy policy) {
818 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700819 }
820
821 @Override
822 public List<Policy> getPolicies() {
823 return policyHandler.getPolicies();
824 }
825
Saurav Das07c74602016-04-27 18:35:50 -0700826 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700827 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
828 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700829 }
830
831 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800832 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700833 return l2TunnelHandler.getL2Tunnels();
834 }
835
836 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800837 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700838 return l2TunnelHandler.getL2Policies();
839 }
840
Saurav Dasdebcf882018-04-06 20:16:01 -0700841 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700842 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700843 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
844
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700845 // get both added and pending pseudowires
846 List<L2TunnelDescription> pseudowires = new ArrayList<>();
847 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
848 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700849 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700850
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700851 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
852
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700853 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
854 L2TunnelHandler.Result res;
855 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
856 res = addPseudowire(pw);
857 if (res != L2TunnelHandler.Result.SUCCESS) {
858 log.error("Pseudowire with id {} can not be instantiated !", res);
859 retRes = res;
860 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700861 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700862
863 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700864 }
865
866 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800867 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700868 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700869 }
870
871 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800872 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700873 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700874 }
875
876 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700877 public void rerouteNetwork() {
878 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700879 }
880
Charles Chand7844e52016-10-20 17:02:44 -0700881 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800882 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
883 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800884 deviceConfiguration.getRouters().forEach(device ->
885 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700886 return deviceSubnetMap;
887 }
888
Saurav Das62ae6792017-05-15 15:34:25 -0700889
890 @Override
891 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
892 if (defaultRoutingHandler != null) {
893 return defaultRoutingHandler.getCurrentEmcpSpgMap();
894 } else {
895 return null;
896 }
897 }
898
899 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700900 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das261c3002017-06-13 15:35:54 -0700901 if (dsNextObjStore != null) {
902 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700903 } else {
904 return ImmutableMap.of();
905 }
906 }
907
Saurav Dasfbe74572017-08-03 18:30:35 -0700908 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700909 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
910 if (vlanNextObjStore != null) {
911 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
912 } else {
913 return ImmutableMap.of();
914 }
915 }
916
917 @Override
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000918 public ImmutableMap<MacVlanNextObjectiveStoreKey, Integer> getMacVlanNextObjStore() {
919 if (macVlanNextObjStore != null) {
920 return ImmutableMap.copyOf(macVlanNextObjStore.entrySet());
921 } else {
922 return ImmutableMap.of();
923 }
924 }
925
926 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700927 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
928 if (portNextObjStore != null) {
929 return ImmutableMap.copyOf(portNextObjStore.entrySet());
930 } else {
931 return ImmutableMap.of();
932 }
933 }
934
935 @Override
936 public ImmutableMap<String, NextObjective> getPwInitNext() {
937 if (l2TunnelHandler != null) {
938 return l2TunnelHandler.getInitNext();
939 } else {
940 return ImmutableMap.of();
941 }
942 }
943
944 @Override
945 public ImmutableMap<String, NextObjective> getPwTermNext() {
946 if (l2TunnelHandler != null) {
947 return l2TunnelHandler.getTermNext();
948 } else {
949 return ImmutableMap.of();
950 }
951 }
952
953 @Override
954 public void invalidateNextObj(int nextId) {
955 if (dsNextObjStore != null) {
956 dsNextObjStore.entrySet().forEach(e -> {
957 if (e.getValue().nextId() == nextId) {
958 dsNextObjStore.remove(e.getKey());
959 }
960 });
961 }
962 if (vlanNextObjStore != null) {
963 vlanNextObjStore.entrySet().forEach(e -> {
964 if (e.getValue() == nextId) {
965 vlanNextObjStore.remove(e.getKey());
966 }
967 });
968 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000969 if (macVlanNextObjStore != null) {
970 macVlanNextObjStore.entrySet().forEach(e -> {
971 if (e.getValue() == nextId) {
972 macVlanNextObjStore.remove(e.getKey());
973 }
974 });
975 }
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700976 if (portNextObjStore != null) {
977 portNextObjStore.entrySet().forEach(e -> {
978 if (e.getValue() == nextId) {
979 portNextObjStore.remove(e.getKey());
980 }
981 });
982 }
983 if (mcastHandler != null) {
984 mcastHandler.removeNextId(nextId);
985 }
986 if (l2TunnelHandler != null) {
987 l2TunnelHandler.removeNextId(nextId);
988 }
989 if (xconnectService != null) {
990 xconnectService.removeNextId(nextId);
991 }
992 }
993
994 @Override
Saurav Dasfbe74572017-08-03 18:30:35 -0700995 public void verifyGroups(DeviceId id) {
996 DefaultGroupHandler gh = groupHandlerMap.get(id);
997 if (gh != null) {
998 gh.triggerBucketCorrector();
999 }
1000 }
1001
Saurav Das6430f412018-01-25 09:49:01 -08001002 @Override
1003 public ImmutableMap<Link, Boolean> getSeenLinks() {
1004 return linkHandler.getSeenLinks();
1005 }
1006
1007 @Override
1008 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
1009 return linkHandler.getDownedPorts();
1010 }
1011
Pier Luigi0f9635b2018-01-15 18:06:43 +01001012 @Override
1013 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -07001014 return mcastHandler.getNextIds(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +01001015 }
1016
1017 @Override
Piere99511d2018-04-19 16:47:06 +02001018 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
1019 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
1020 }
1021
1022 @Override
Pier71c55772018-04-17 17:25:22 +02001023 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
1024 ConnectPoint sourcecp) {
1025 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
1026 }
1027
1028 @Override
Pierdb27b8d2018-04-17 16:29:56 +02001029 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
1030 return mcastHandler.getMcastLeaders(mcastIp);
1031 }
1032
Charles Chanb13e0702018-04-17 18:56:53 -07001033 @Override
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001034 public Map<DeviceId, List<McastFilteringObjStoreKey>> getMcastFilters() {
1035 return mcastHandler.getMcastFilters();
1036 }
1037
1038 @Override
Charles Chanb13e0702018-04-17 18:56:53 -07001039 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
1040 return defaultRoutingHandler == null ? ImmutableMap.of() :
1041 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
1042 }
1043
1044 @Override
1045 public Map<DeviceId, Boolean> getShouldProgramCache() {
1046 return defaultRoutingHandler == null ? ImmutableMap.of() :
1047 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
1048 }
1049
Charles Chan8d316332018-06-19 20:31:57 -07001050 @Override
jayakumarthazhath66c9ec12018-10-01 00:51:54 +05301051 public boolean shouldProgram(DeviceId deviceId) {
1052 return defaultRoutingHandler.shouldProgram(deviceId);
1053 }
1054
1055 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -07001056 public ApplicationId appId() {
1057 return appId;
1058 }
1059
1060 /**
1061 * Returns the device configuration.
1062 *
1063 * @return device configuration
1064 */
1065 public DeviceConfiguration deviceConfiguration() {
1066 return deviceConfiguration;
1067 }
1068
1069 /**
Saurav Das261c3002017-06-13 15:35:54 -07001070 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -07001071 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001072 *
1073 * @return next objective ID store
1074 */
Saurav Das261c3002017-06-13 15:35:54 -07001075 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1076 dsNextObjStore() {
1077 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -07001078 }
1079
1080 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001081 * Per device next objective ID store with (device id + vlanid) as key.
1082 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001083 *
1084 * @return vlan next object store
1085 */
1086 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1087 return vlanNextObjStore;
1088 }
1089
1090 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001091 * Per device next objective ID store with (device id + MAC address + vlan) as key.
1092 * Used to keep track on L3 Unicast group information for indirect hosts.
1093 *
1094 * @return mac vlan next object store
1095 */
1096 public EventuallyConsistentMap<MacVlanNextObjectiveStoreKey, Integer> macVlanNextObjStore() {
1097 return macVlanNextObjStore;
1098 }
1099
1100 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001101 * Per device next objective ID store with (device id + port + treatment + meta) as key.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001102 * Used to keep track on L2 interface group and L3 unicast group information for direct hosts.
Ray Milkeyb85de082017-04-05 09:42:04 -07001103 *
1104 * @return port next object store.
1105 */
1106 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1107 return portNextObjStore;
1108 }
1109
1110 /**
Saurav Das261c3002017-06-13 15:35:54 -07001111 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1112 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -07001113 *
1114 * @return MPLS-ECMP value
1115 */
1116 public boolean getMplsEcmp() {
1117 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1118 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1119 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1120 }
1121
1122 /**
sangho80f1f892015-05-19 11:57:42 -07001123 * Returns the tunnel object with the tunnel ID.
1124 *
1125 * @param tunnelId Tunnel ID
1126 * @return Tunnel reference
1127 */
sangho27462c62015-05-14 00:39:53 -07001128 public Tunnel getTunnel(String tunnelId) {
1129 return tunnelHandler.getTunnel(tunnelId);
1130 }
1131
Charles Chan8d316332018-06-19 20:31:57 -07001132 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +01001133 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -07001134 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1135 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -07001136 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1137 }
1138
Charles Chan8d316332018-06-19 20:31:57 -07001139 @Override
1140 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001141 SegmentRoutingDeviceConfig deviceConfig =
1142 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1143 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1144 }
Charles Chan8d316332018-06-19 20:31:57 -07001145
1146 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -07001147 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001148 SegmentRoutingDeviceConfig deviceConfig =
1149 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1150 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1151 }
1152
1153 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -07001154 * Returns locations of given resolved route.
1155 *
1156 * @param resolvedRoute resolved route
1157 * @return locations of nexthop. Might be empty if next hop is not found
1158 */
Charles Chan19b70032019-04-17 14:20:26 -07001159 public Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
Charles Chanf0ae41e2017-08-23 13:55:39 -07001160 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1161 return Optional.ofNullable(hostService.getHost(hostId))
1162 .map(Host::locations).orElse(Sets.newHashSet())
1163 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1164 }
1165
1166 /**
Charles Chan90772a72017-02-08 15:52:08 -08001167 * Returns vlan port map of given device.
1168 *
1169 * @param deviceId device id
1170 * @return vlan-port multimap
1171 */
1172 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1173 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1174
1175 interfaceService.getInterfaces().stream()
1176 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1177 .forEach(intf -> {
1178 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -07001179 intf.vlanTagged().forEach(vlanTagged ->
1180 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1181 );
Charles Chan90772a72017-02-08 15:52:08 -08001182 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1183 });
1184 vlanPortMap.removeAll(VlanId.NONE);
1185
1186 return vlanPortMap;
1187 }
1188
1189 /**
Charles Chan10b0fb72017-02-02 16:20:42 -08001190 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -08001191 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -07001192 *
1193 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -08001194 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -08001195 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -07001196 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001197 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -07001198 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -08001199 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1200 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -07001201 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -08001202 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -08001203 + "device {} not found", deviceId);
1204 return -1;
1205 }
1206 }
1207
1208 /**
1209 * Returns the next objective ID for the given portNumber, given the treatment.
1210 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -07001211 * would result in different objectives. If the next object does not exist,
1212 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -08001213 *
1214 * @param deviceId Device ID
1215 * @param portNum port number on device for which NextObjective is queried
1216 * @param treatment the actions to apply on the packets (should include outport)
1217 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -07001218 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -07001219 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -08001220 */
1221 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1222 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -07001223 TrafficSelector meta,
1224 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -08001225 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1226 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -07001227 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -08001228 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -08001229 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1230 + " not found", deviceId);
1231 return -1;
1232 }
1233 }
1234
Saurav Das62ae6792017-05-15 15:34:25 -07001235 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001236 * Returns the next Objective ID for the given mac and vlan, given the treatment.
1237 * There could be multiple different treatments to the same outport, which
1238 * would result in different objectives. If the next object does not exist,
1239 * and should be created, a new one is created and its id is returned.
1240 *
1241 * @param deviceId Device ID
1242 * @param macAddr mac of host for which Next ID is required.
1243 * @param vlanId vlan of host for which Next ID is required.
Ruchi Sahota07869322019-05-09 17:26:14 -04001244 * @param port port with which to create the Next Obj.
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001245 * @param createIfMissing true if a next object should be created if not found
1246 * @return next objective ID or -1 if an error occurred during retrieval or creation
1247 */
1248 public int getMacVlanNextObjectiveId(DeviceId deviceId, MacAddress macAddr, VlanId vlanId,
Ruchi Sahota07869322019-05-09 17:26:14 -04001249 PortNumber port, boolean createIfMissing) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001250 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1251 if (ghdlr != null) {
Ruchi Sahota07869322019-05-09 17:26:14 -04001252 return ghdlr.getMacVlanNextObjectiveId(macAddr, vlanId, port, createIfMissing);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001253 } else {
1254 log.warn("getMacVlanNextObjectiveId query - groupHandler for device {}"
1255 + " not found", deviceId);
1256 return -1;
1257 }
1258 }
1259
1260 /**
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001261 * Updates the next objective for the given nextId .
1262 *
1263 * @param deviceId Device ID
1264 * @param hostMac mac of host for which Next obj is to be updated.
1265 * @param hostVlanId vlan of host for which Next obj is to be updated.
1266 * @param port port with which to update the Next Obj.
1267 * @param nextId of Next Obj which needs to be updated.
1268 */
1269 public void updateMacVlanTreatment(DeviceId deviceId, MacAddress hostMac,
1270 VlanId hostVlanId, PortNumber port, int nextId) {
pierf0e37ec2019-11-26 11:48:48 +01001271 // Check if we are the king of this device
1272 // just one instance should perform this update
1273 if (!defaultRoutingHandler.shouldProgram(deviceId)) {
1274 log.debug("This instance is not handling the routing towards the "
1275 + "device {}", deviceId);
1276 return;
1277 }
1278 // Get the handler and perform the update
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001279 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1280 if (ghdlr != null) {
1281 ghdlr.updateL3UcastGroupBucket(hostMac, hostVlanId, port, nextId);
1282 } else {
1283 log.warn("updateL3UcastGroupBucket query - groupHandler for device {}"
1284 + " not found", deviceId);
1285 }
1286 }
1287
1288
1289 /**
Saurav Das62ae6792017-05-15 15:34:25 -07001290 * Returns the group handler object for the specified device id.
1291 *
1292 * @param devId the device identifier
1293 * @return the groupHandler object for the device id, or null if not found
1294 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001295 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001296 return groupHandlerMap.get(devId);
1297 }
1298
1299 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001300 * Returns the default routing handler object.
1301 *
1302 * @return the default routing handler object
1303 */
1304 public DefaultRoutingHandler getRoutingHandler() {
1305 return defaultRoutingHandler;
1306 }
1307
sangho80f11cb2015-04-01 13:05:26 -07001308 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001309 @Override
1310 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001311 packetExecutor.execute(() -> processPacketInternal(context));
1312 }
sangho80f11cb2015-04-01 13:05:26 -07001313
Charles Chan77cdde42018-05-08 21:35:50 -07001314 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001315 if (context.isHandled()) {
1316 return;
1317 }
1318
1319 InboundPacket pkt = context.inPacket();
1320 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001321
1322 if (ethernet == null) {
1323 return;
1324 }
1325
Saurav Das261c3002017-06-13 15:35:54 -07001326 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1327 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001328 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001329 log.warn("Received unexpected ARP packet on {}",
1330 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001331 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001332 return;
sangho80f11cb2015-04-01 13:05:26 -07001333 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001334 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1335 //ipHandler.addToPacketBuffer(ipv4Packet);
1336 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1337 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001338 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001339 // NOTE: We don't support IP learning at this moment so this
1340 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001341 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001342 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001343 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1344 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001345 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001346 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001347 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1348 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1349 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1350 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1351 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1352 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001353 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001354 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001355 }
1356 } else {
1357 // NOTE: We don't support IP learning at this moment so this
1358 // is not necessary. Also it causes duplication of DHCPv6 packets.
1359 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1360 }
sangho80f11cb2015-04-01 13:05:26 -07001361 }
1362 }
1363 }
1364
sangho80f11cb2015-04-01 13:05:26 -07001365 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001366 private Event event;
1367
1368 InternalEventHandler(Event event) {
1369 this.event = event;
1370 }
1371
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001372 @Override
sangho80f11cb2015-04-01 13:05:26 -07001373 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001374 try {
1375 // TODO We should also change SR routing and PW to listen to TopologyEvents
1376 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1377 event.type() == LinkEvent.Type.LINK_UPDATED) {
1378 linkHandler.processLinkAdded((Link) event.subject());
1379 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1380 linkHandler.processLinkRemoved((Link) event.subject());
1381 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1382 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1383 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1384 DeviceId deviceId = ((Device) event.subject()).id();
1385 if (deviceService.isAvailable(deviceId)) {
1386 log.info("** DEVICE UP Processing device event {} "
1387 + "for available device {}",
1388 event.type(), ((Device) event.subject()).id());
1389 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001390 } else {
Charles Chanb8f3af52018-08-29 21:21:51 -07001391 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1392 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1393 // The device will later on being marked as available once the pipeline is pushed
1394 // to the device.
1395 log.info("** DEVICE ADDED but unavailable. Ignore");
1396 return;
1397 }
Charles Chan52003922018-04-05 16:31:15 -07001398 log.info(" ** DEVICE DOWN Processing device event {}"
1399 + " for unavailable device {}",
1400 event.type(), ((Device) event.subject()).id());
1401 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001402 }
Charles Chan52003922018-04-05 16:31:15 -07001403 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1404 // typically these calls come when device is added first time
1405 // so port filtering rules are handled at the device_added event.
1406 // port added calls represent all ports on the device,
1407 // enabled or not.
1408 log.trace("** PORT ADDED {}/{} -> {}",
1409 ((DeviceEvent) event).subject().id(),
1410 ((DeviceEvent) event).port().number(),
1411 event.type());
1412 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1413 // these calls happen for every subsequent event
1414 // ports enabled, disabled, switch goes away, comes back
1415 log.info("** PORT UPDATED {}/{} -> {}",
1416 event.subject(),
1417 ((DeviceEvent) event).port(),
1418 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001419 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001420 ((DeviceEvent) event).port());
Harshada Chaundkar9204f312019-07-02 16:01:24 +00001421 mcastHandler.processPortUpdate(((Device) event.subject()),
1422 ((DeviceEvent) event).port());
Charles Chan52003922018-04-05 16:31:15 -07001423 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1424 // Process topology event, needed for all modules relying on
1425 // topology service for path computation
1426 TopologyEvent topologyEvent = (TopologyEvent) event;
1427 log.info("Processing topology event {}, topology age {}, reasons {}",
1428 event.type(), topologyEvent.subject().time(),
1429 topologyEvent.reasons().size());
1430 topologyHandler.processTopologyChange(topologyEvent.reasons());
1431 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1432 hostHandler.processHostAddedEvent((HostEvent) event);
1433 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1434 hostHandler.processHostMovedEvent((HostEvent) event);
1435 routeHandler.processHostMovedEvent((HostEvent) event);
Charles Chana2ccb582019-11-25 09:47:22 -08001436 } else if (event.type() == HostEvent.Type.HOST_AUX_MOVED) {
1437 hostHandler.processHostMovedEvent((HostEvent) event);
1438 // TODO RouteHandler also needs to process this event in order to
1439 // support nexthops that has auxLocations
Charles Chan52003922018-04-05 16:31:15 -07001440 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1441 hostHandler.processHostRemovedEvent((HostEvent) event);
1442 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1443 hostHandler.processHostUpdatedEvent((HostEvent) event);
1444 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1445 routeHandler.processRouteAdded((RouteEvent) event);
1446 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1447 routeHandler.processRouteUpdated((RouteEvent) event);
1448 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1449 routeHandler.processRouteRemoved((RouteEvent) event);
1450 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1451 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1452 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1453 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1454 event.type() == McastEvent.Type.SINKS_ADDED ||
1455 event.type() == McastEvent.Type.SINKS_REMOVED ||
1456 event.type() == McastEvent.Type.ROUTE_ADDED ||
1457 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1458 mcastHandler.processMcastEvent((McastEvent) event);
1459 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1460 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1461 Class configClass = netcfgEvent.configClass();
1462 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1463 appCfgHandler.processAppConfigAdded(netcfgEvent);
1464 log.info("App config event .. configuring network");
1465 cfgListener.configureNetwork();
1466 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1467 log.info("Segment Routing Device Config added for {}", event.subject());
1468 cfgListener.configureNetwork();
Charles Chan52003922018-04-05 16:31:15 -07001469 } else if (configClass.equals(InterfaceConfig.class)) {
1470 log.info("Interface Config added for {}", event.subject());
1471 cfgListener.configureNetwork();
1472 } else {
1473 log.error("Unhandled config class: {}", configClass);
1474 }
1475 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1476 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1477 Class configClass = netcfgEvent.configClass();
1478 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1479 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1480 log.info("App config event .. configuring network");
1481 cfgListener.configureNetwork();
1482 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1483 log.info("Segment Routing Device Config updated for {}", event.subject());
1484 createOrUpdateDeviceConfiguration();
Charles Chan52003922018-04-05 16:31:15 -07001485 } else if (configClass.equals(InterfaceConfig.class)) {
1486 log.info("Interface Config updated for {}", event.subject());
1487 createOrUpdateDeviceConfiguration();
1488 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1489 (InterfaceConfig) netcfgEvent.prevConfig().get());
1490 } else {
1491 log.error("Unhandled config class: {}", configClass);
1492 }
1493 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1494 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1495 Class configClass = netcfgEvent.configClass();
1496 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1497 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1498 log.info("App config event .. configuring network");
1499 cfgListener.configureNetwork();
1500 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1501 // TODO Handle sr device config removal
1502 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
Charles Chan52003922018-04-05 16:31:15 -07001503 } else if (configClass.equals(InterfaceConfig.class)) {
1504 // TODO Handle interface removal
1505 log.info("InterfaceConfig removal is not handled in current implementation");
1506 } else {
1507 log.error("Unhandled config class: {}", configClass);
1508 }
Saurav Das00e553b2018-04-21 17:19:48 -07001509 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1510 MastershipEvent me = (MastershipEvent) event;
1511 DeviceId deviceId = me.subject();
1512 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1513 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1514 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1515 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1516 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1517 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan52003922018-04-05 16:31:15 -07001518 } else {
1519 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001520 }
Charles Chan52003922018-04-05 16:31:15 -07001521 } catch (Exception e) {
1522 log.error("SegmentRouting event handler thread thrown an exception: {}",
1523 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001524 }
sangho80f11cb2015-04-01 13:05:26 -07001525 }
1526 }
1527
Saurav Dase6c448a2018-01-18 12:07:33 -08001528 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001529 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001530
1531 // NOTE: Punt ARP/NDP even when the device is not configured.
1532 // Host learning without network config is required for CORD config generator.
1533 routingRulePopulator.populateIpPunts(device.id());
1534 routingRulePopulator.populateArpNdpPunts(device.id());
1535
Charles Chan319d1a22015-11-03 10:42:14 -08001536 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001537 log.warn("Device configuration unavailable. Device {} will be "
1538 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001539 return;
1540 }
Charles Chan72779502016-04-23 17:36:10 -07001541 processDeviceAddedInternal(device.id());
1542 }
1543
1544 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001545 // Irrespective of whether the local is a MASTER or not for this device,
1546 // we need to create a SR-group-handler instance. This is because in a
1547 // multi-instance setup, any instance can initiate forwarding/next-objectives
1548 // for any switch (even if this instance is a SLAVE or not even connected
1549 // to the switch). To handle this, a default-group-handler instance is necessary
1550 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001551 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1552 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001553 DefaultGroupHandler groupHandler;
1554 try {
1555 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001556 createGroupHandler(deviceId,
1557 appId,
1558 deviceConfiguration,
1559 linkService,
1560 flowObjectiveService,
1561 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001562 } catch (DeviceConfigNotFoundException e) {
1563 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1564 return;
1565 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001566 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001567 deviceId);
1568 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001569 }
Saurav Dasb149be12016-06-07 10:08:06 -07001570
Charles Chan72779502016-04-23 17:36:10 -07001571 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001572 defaultRoutingHandler.populatePortAddressingRules(deviceId);
pierf331a492020-01-07 15:39:39 +01001573 defaultRoutingHandler.purgeSeenBeforeRoutes(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001574 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001575 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001576 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001577 }
Charles Chan82ab1932016-01-30 23:22:37 -08001578
Charles Chandebfea32016-10-24 14:52:01 -07001579 appCfgHandler.init(deviceId);
Charles Chan074fae62018-04-29 18:11:37 -07001580 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1581 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sangho80f11cb2015-04-01 13:05:26 -07001582 }
1583
Saurav Dasc3604f12016-03-23 11:22:49 -07001584 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001585 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001586 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001587 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001588 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001589 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001590 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001591 macVlanNextObjStore.entrySet().stream()
1592 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1593 .forEach(entry -> macVlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001594 portNextObjStore.entrySet().stream()
1595 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001596 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001597 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001598
Saurav Dasfbe74572017-08-03 18:30:35 -07001599 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1600 if (gh != null) {
1601 gh.shutdown();
1602 }
Saurav Das62ae6792017-05-15 15:34:25 -07001603 // Note that a switch going down is associated with all of its links
1604 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001605 // while the link-downs are ignored. We cannot rely on the ordering of
1606 // events - i.e we cannot expect all link-downs to come before the
1607 // switch down - so we purge all seen-links for the switch before
1608 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001609 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001610 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001611 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001612
1613 // Cleanup all internal groupHandler stores for this device. Should be
1614 // done after all rerouting or rehashing has been completed
1615 groupHandlerMap.entrySet()
1616 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001617 }
1618
Saurav Das49368392018-04-23 18:42:12 -07001619 /**
1620 * Purge the destinationSet nextObjective store of entries with this device
1621 * as key. Erases app-level knowledge of hashed groups in this device.
1622 *
1623 * @param devId the device identifier
1624 */
Saurav Das00e553b2018-04-21 17:19:48 -07001625 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001626 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001627 dsNextObjStore.entrySet().stream()
1628 .filter(entry -> entry.getKey().deviceId().equals(devId))
1629 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1630 }
1631
Saurav Dasec683dc2018-04-27 18:42:30 -07001632 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001633 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1634 log.warn("Device configuration uploading. Not handling port event for"
1635 + "dev: {} port: {}", device.id(), port.number());
1636 return;
1637 }
Saurav Dasf9332192017-02-18 14:05:44 -08001638
Saurav Dasec683dc2018-04-27 18:42:30 -07001639 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1640 lastEdgePortEvent = Instant.now();
1641 }
1642
Saurav Dasf9332192017-02-18 14:05:44 -08001643 if (!mastershipService.isLocalMaster(device.id())) {
1644 log.debug("Not master for dev:{} .. not handling port updated event"
1645 + "for port {}", device.id(), port.number());
1646 return;
1647 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001648 processPortUpdated(device.id(), port);
1649 }
Saurav Dasf9332192017-02-18 14:05:44 -08001650
Saurav Dasec683dc2018-04-27 18:42:30 -07001651 /**
1652 * Adds or remove filtering rules for the given switchport. If switchport is
1653 * an edge facing port, additionally handles host probing and broadcast
1654 * rules. Must be called by local master of device.
1655 *
1656 * @param deviceId the device identifier
1657 * @param port the port to update
1658 */
1659 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001660 // first we handle filtering rules associated with the port
1661 if (port.isEnabled()) {
1662 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001663 deviceId, port.number());
1664 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001665 } else {
1666 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001667 deviceId, port.number());
1668 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001669 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001670
1671 // portUpdated calls are for ports that have gone down or up. For switch
1672 // to switch ports, link-events should take care of any re-routing or
1673 // group editing necessary for port up/down. Here we only process edge ports
1674 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001675 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001676 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1677 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1678 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001679
Saurav Das3fb28272017-03-04 16:08:47 -08001680 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001681 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001682 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001683 return;
1684 }
Saurav Das3fb28272017-03-04 16:08:47 -08001685 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001686 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001687 }
1688 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001689 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001690 }
1691 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001692 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001693 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001694 }
1695
Saurav Dasec683dc2018-04-27 18:42:30 -07001696 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001697 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001698 boolean portUp = port.isEnabled();
1699 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001700 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001701 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001702 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001703 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001704 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001705 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001706 }
1707
Saurav Dasec683dc2018-04-27 18:42:30 -07001708 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001709 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001710 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001711 } else {
1712 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001713 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001714 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001715 }
1716 }
sangho27462c62015-05-14 00:39:53 -07001717
Charles Chan8ca5a122017-10-20 16:06:55 -07001718 private void createOrUpdateDeviceConfiguration() {
1719 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001720 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001721 deviceConfiguration = new DeviceConfiguration(this);
1722 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001723 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001724 deviceConfiguration.updateConfig();
1725 }
1726 }
1727
Charles Chanfbcb8812018-04-18 18:41:05 -07001728 private void createOrUpdateDefaultRoutingHandler() {
1729 if (defaultRoutingHandler == null) {
1730 log.info("Creating new DefaultRoutingHandler");
1731 defaultRoutingHandler = new DefaultRoutingHandler(this);
1732 } else {
1733 log.info("Updating DefaultRoutingHandler");
1734 defaultRoutingHandler.update(this);
1735 }
1736 }
1737
Pier Ventreb6a7f342016-11-26 21:05:22 -08001738 /**
1739 * Registers the given connect point with the NRS, this is necessary
1740 * to receive the NDP and ARP packets from the NRS.
1741 *
1742 * @param portToRegister connect point to register
1743 */
1744 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001745 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001746 portToRegister,
1747 neighbourHandler,
1748 appId
1749 );
1750 }
1751
Charles Chan72f556a2015-10-05 17:50:33 -07001752 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001753 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001754 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001755
Charles Chanb7f75ac2016-01-11 18:28:54 -08001756 /**
1757 * Constructs the internal network config listener.
1758 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001759 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001760 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001761 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001762 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001763 }
1764
Charles Chanb7f75ac2016-01-11 18:28:54 -08001765 /**
1766 * Reads network config and initializes related data structure accordingly.
1767 */
Charles Chan873661e2017-11-30 15:37:50 -08001768 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001769 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001770
1771 // Setting handling of network configuration events completable future
1772 // The completable future is needed because of the async behaviour of the configureNetwork,
1773 // listener registration and event arrival
1774 // Enables us to buffer the events and execute them when the configure network is done.
Ray Milkey521e4392018-11-16 15:15:14 -08001775 synchronized (networkConfigCompletionLock) {
1776 networkConfigCompletion = new CompletableFuture<>();
Andrea Campanella060cad82018-04-17 12:09:34 +02001777
Ray Milkey521e4392018-11-16 15:15:14 -08001778 // add a small delay to absorb multiple network config added notifications
1779 if (!programmingScheduled.get()) {
1780 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1781 programmingScheduled.set(true);
1782 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1783 }
1784
1785 createOrUpdateDeviceConfiguration();
1786
1787 arpHandler = new ArpHandler(srManager);
1788 icmpHandler = new IcmpHandler(srManager);
1789 ipHandler = new IpHandler(srManager);
1790 routingRulePopulator = new RoutingRulePopulator(srManager);
1791 createOrUpdateDefaultRoutingHandler();
1792
1793 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1794 groupHandlerMap, tunnelStore);
1795 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1796 flowObjectiveService,
1797 tunnelHandler, policyStore);
1798 networkConfigCompletion.complete(true);
Andrea Campanella060cad82018-04-17 12:09:34 +02001799 }
1800
Charles Chan72779502016-04-23 17:36:10 -07001801 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001802
Charles Chane7c61022015-10-07 14:21:45 -07001803 }
1804
Charles Chan72f556a2015-10-05 17:50:33 -07001805 @Override
1806 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001807 if (mainEventExecutor == null) {
1808 return;
1809 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001810 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan3f4aca62018-03-21 16:57:47 -07001811 switch (event.type()) {
1812 case CONFIG_ADDED:
1813 case CONFIG_UPDATED:
1814 case CONFIG_REMOVED:
1815 log.trace("Schedule Network Config event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001816 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1817 mainEventExecutor.execute(new InternalEventHandler(event));
1818 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001819 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001820 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001821 break;
1822 default:
1823 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001824 }
1825 }
Saurav Das261c3002017-06-13 15:35:54 -07001826
Charles Chanc4a68c32018-01-03 16:26:32 -08001827 @Override
1828 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001829 if (event.type() == CONFIG_REGISTERED ||
1830 event.type() == CONFIG_UNREGISTERED) {
1831 log.debug("Ignore event {} due to type mismatch", event);
1832 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001833 }
Saurav Dase321cff2018-02-09 17:26:45 -08001834
1835 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1836 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
Charles Chana01d57c2019-07-19 16:25:38 -07001837 !event.configClass().equals(InterfaceConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001838 log.debug("Ignore event {} due to class mismatch", event);
1839 return false;
1840 }
1841
1842 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001843 }
1844
Saurav Das261c3002017-06-13 15:35:54 -07001845 private final class ConfigChange implements Runnable {
1846 @Override
1847 public void run() {
1848 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001849 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001850 for (Device device : deviceService.getDevices()) {
1851 processDeviceAdded(device);
1852 }
1853 defaultRoutingHandler.startPopulationProcess();
1854 }
1855 }
Charles Chan72f556a2015-10-05 17:50:33 -07001856 }
Charles Chanf4586112015-11-09 16:37:23 -08001857
Charles Chan3f4aca62018-03-21 16:57:47 -07001858 private class InternalLinkListener implements LinkListener {
1859 @Override
1860 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001861 if (mainEventExecutor == null) {
1862 return;
1863 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001864 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1865 event.type() == LinkEvent.Type.LINK_UPDATED ||
1866 event.type() == LinkEvent.Type.LINK_REMOVED) {
1867 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001868 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1869 mainEventExecutor.execute(new InternalEventHandler(event));
1870 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001871 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001872 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001873 }
1874 }
1875 }
1876
1877 private class InternalDeviceListener implements DeviceListener {
1878 @Override
1879 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001880 if (mainEventExecutor == null) {
1881 return;
1882 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001883 switch (event.type()) {
1884 case DEVICE_ADDED:
1885 case PORT_UPDATED:
1886 case PORT_ADDED:
1887 case DEVICE_UPDATED:
1888 case DEVICE_AVAILABILITY_CHANGED:
1889 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001890 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1891 mainEventExecutor.execute(new InternalEventHandler(event));
1892 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001893 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001894 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001895 break;
1896 default:
1897 }
1898 }
1899 }
1900
1901 private class InternalTopologyListener implements TopologyListener {
1902 @Override
1903 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001904 if (mainEventExecutor == null) {
1905 return;
1906 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001907 switch (event.type()) {
1908 case TOPOLOGY_CHANGED:
1909 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001910 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1911 mainEventExecutor.execute(new InternalEventHandler(event));
1912 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001913 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001914 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001915 break;
1916 default:
1917 }
1918 }
1919 }
1920
Charles Chanf4586112015-11-09 16:37:23 -08001921 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001922 @Override
1923 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001924 if (hostEventExecutor == null) {
1925 return;
1926 }
Charles Chanf4586112015-11-09 16:37:23 -08001927 switch (event.type()) {
1928 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001929 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001930 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001931 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001932 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001933 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08001934 break;
1935 default:
1936 log.warn("Unsupported host event type: {}", event.type());
1937 break;
1938 }
1939 }
1940 }
1941
Charles Chanc91c8782016-03-30 17:54:24 -07001942 private class InternalMcastListener implements McastListener {
1943 @Override
1944 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001945 if (mcastEventExecutor == null) {
1946 return;
1947 }
Charles Chanc91c8782016-03-30 17:54:24 -07001948 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07001949 case SOURCES_ADDED:
1950 case SOURCES_REMOVED:
1951 case SINKS_ADDED:
1952 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07001953 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02001954 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001955 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001956 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01001957 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001958 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001959 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07001960 break;
1961 }
1962 }
1963 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001964
Charles Chandebfea32016-10-24 14:52:01 -07001965 private class InternalRouteEventListener implements RouteListener {
1966 @Override
1967 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001968 if (routeEventExecutor == null) {
1969 return;
1970 }
Charles Chandebfea32016-10-24 14:52:01 -07001971 switch (event.type()) {
1972 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07001973 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07001974 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07001975 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001976 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001977 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07001978 break;
Charles Chandebfea32016-10-24 14:52:01 -07001979 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001980 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07001981 break;
1982 }
1983 }
1984 }
Saurav Das62ae6792017-05-15 15:34:25 -07001985
Charles Chanfbcb8812018-04-18 18:41:05 -07001986 private class InternalMastershipListener implements MastershipListener {
1987 @Override
1988 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001989 if (mainEventExecutor == null) {
1990 return;
1991 }
Charles Chanfbcb8812018-04-18 18:41:05 -07001992 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07001993 case MASTER_CHANGED:
1994 log.debug("Mastership event: {}/{}", event.subject(),
1995 event.roleInfo());
1996 mainEventExecutor.execute(new InternalEventHandler(event));
1997 break;
1998 case BACKUPS_CHANGED:
1999 case SUSPENDED:
2000 default:
2001 log.debug("Mastership event type {} not handled", event.type());
2002 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07002003 }
2004 }
2005 }
2006
Saurav Das00e553b2018-04-21 17:19:48 -07002007 class InternalClusterListener implements ClusterEventListener {
2008 private Instant lastClusterEvent = Instant.EPOCH;
2009
2010 long timeSinceLastClusterEvent() {
2011 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
2012 }
2013
2014 @Override
2015 public void event(ClusterEvent event) {
2016 switch (event.type()) {
2017 case INSTANCE_ACTIVATED:
2018 case INSTANCE_ADDED:
2019 case INSTANCE_READY:
2020 log.debug("Cluster event {} ignored", event.type());
2021 break;
2022 case INSTANCE_DEACTIVATED:
2023 case INSTANCE_REMOVED:
2024 log.info("** Cluster event {}", event.type());
2025 lastClusterEvent = Instant.now();
2026 break;
2027 default:
2028 break;
2029 }
2030
2031 }
2032
2033 }
2034
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002035 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
2036 try {
2037 Set<Interface> intfs = conf.getInterfaces();
2038 Set<Interface> prevIntfs = prevConf.getInterfaces();
2039
2040 // Now we only handle one interface config at each port.
2041 if (intfs.size() != 1 || prevIntfs.size() != 1) {
2042 log.warn("Interface update aborted - one at a time is allowed, " +
2043 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
2044 return;
2045 }
2046
Andrea Campanella060cad82018-04-17 12:09:34 +02002047 //The system is in an incoherent state, abort
2048 if (defaultRoutingHandler == null) {
2049 log.warn("Interface update aborted, defaultRoutingHandler is null");
2050 return;
2051 }
2052
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002053 Interface intf = intfs.stream().findFirst().get();
2054 Interface prevIntf = prevIntfs.stream().findFirst().get();
2055
2056 DeviceId deviceId = intf.connectPoint().deviceId();
2057 PortNumber portNum = intf.connectPoint().port();
2058
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002059 removeSubnetConfig(prevIntf.connectPoint(),
2060 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
2061 new HashSet<>(intf.ipAddressesList())));
2062
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002063 if (!prevIntf.vlanNative().equals(VlanId.NONE)
2064 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
2065 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
2066 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
2067 // Update filtering objective and L2IG group bucket
2068 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
2069 } else {
2070 // RemoveVlanNative
2071 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
2072 }
2073 }
2074
2075 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
2076 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2077 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2078 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
2079 // Update filtering objective and L2IG group bucket
2080 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
2081 } else {
2082 // RemoveVlanUntagged
2083 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
2084 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002085 }
2086
2087 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2088 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002089 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2090 .filter(i -> !intf.vlanUntagged().equals(i))
2091 .filter(i -> !intf.vlanNative().equals(i))
2092 .forEach(vlanId -> updateVlanConfigInternal(
2093 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002094 }
2095
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002096 if (!intf.vlanNative().equals(VlanId.NONE)
2097 && !prevIntf.vlanNative().equals(intf.vlanNative())
2098 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2099 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2100 // Update filtering objective and L2IG group bucket
2101 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2102 } else {
2103 // AddVlanNative
2104 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2105 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002106 }
2107
2108 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2109 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002110 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2111 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2112 .filter(i -> !prevIntf.vlanNative().equals(i))
2113 .forEach(vlanId -> updateVlanConfigInternal(
2114 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002115 );
2116 }
2117
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002118 if (!intf.vlanUntagged().equals(VlanId.NONE)
2119 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2120 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2121 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2122 // Update filtering objective and L2IG group bucket
2123 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2124 } else {
2125 // AddVlanUntagged
2126 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2127 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002128 }
2129 addSubnetConfig(prevIntf.connectPoint(),
2130 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2131 new HashSet<>(prevIntf.ipAddressesList())));
2132 } catch (ConfigException e) {
2133 log.error("Error in configuration");
2134 }
2135 }
2136
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002137 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2138 VlanId vlanId, boolean pushVlan) {
2139 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2140 if (grpHandler == null) {
2141 log.warn("Failed to retrieve group handler for device {}", deviceId);
2142 return;
2143 }
2144
2145 // Update filtering objective for a single port
2146 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2147 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2148
2149 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2150 // Update L2IG bucket of the port
2151 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002152 // Update bridging and unicast routing rule for each host
2153 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2154 vlanId, !pushVlan, false));
2155 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2156 vlanId, pushVlan, true));
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002157 } else {
2158 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2159 }
2160 }
2161
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002162 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2163 VlanId vlanId, boolean pushVlan, boolean install) {
2164 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2165 if (grpHandler == null) {
2166 log.warn("Failed to retrieve group handler for device {}", deviceId);
2167 return;
2168 }
2169
2170 // Update filtering objective for a single port
2171 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2172
2173 // Update filtering objective for multicast ingress port
2174 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2175
2176 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2177
2178 if (nextId != -1 && !install) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002179 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan074fae62018-04-29 18:11:37 -07002180 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2181 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002182 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2183 // only if there is no port configured on that VLAN ID
2184 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2185 // Remove broadcast forwarding rule for the VLAN
2186 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2187 // Remove L2FG for VLAN
2188 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2189 } else {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002190 // Remove a single port from L2FG
2191 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002192 }
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002193 // Remove L2IG of the port
2194 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002195 } else if (install) {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08002196 // Create L2IG of the port
2197 grpHandler.createPortNextObjective(deviceId, portNum, vlanId, pushVlan);
2198 // Create L2 Bridging rule and L3 Unicast rule to the host
2199 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2200 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002201 if (nextId != -1) {
2202 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002203 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002204 } else {
2205 // Create L2FG for VLAN
2206 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2207 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2208 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002209 } else {
2210 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2211 }
2212 }
2213
2214 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2215 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2216 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2217
2218 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2219 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2220 .filter(intf -> !intf.connectPoint().equals(cp))
2221 .flatMap(intf -> intf.ipAddressesList().stream())
2222 .collect(Collectors.toSet());
2223 // 1. Partial subnet population
2224 // Remove routing rules for removed subnet from previous configuration,
2225 // which does not also exist in other interfaces in the same device
2226 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2227 .map(InterfaceIpAddress::subnetAddress)
2228 .collect(Collectors.toSet());
2229
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002230 Set<IpPrefix> subnetsToBeRevoked = ipPrefixSet.stream()
2231 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2232 .collect(Collectors.toSet());
2233
2234 // Check if any of the subnets to be revoked is configured in the pairDevice.
2235 // If any, repopulate the subnet with pairDevice connectPoint instead of revoking.
2236 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2237 if (pairDevice.isPresent()) {
2238 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2239
2240 Set<IpPrefix> subnetsExistingInPairDevice = subnetsToBeRevoked.stream()
2241 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2242 .collect(Collectors.toSet());
2243
2244 // Update the subnets existing in pair device with pair device connect point.
2245 if (!subnetsExistingInPairDevice.isEmpty()) {
2246 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2247 ConnectPoint pairDeviceCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2248 log.debug("Updating the subnets: {} with pairDevice connectPoint as it exists in the Pair device: {}",
2249 subnetsExistingInPairDevice, pairDeviceCp);
2250 defaultRoutingHandler.populateSubnet(Collections.singleton(pairDeviceCp), subnetsExistingInPairDevice);
2251 }
2252
2253 // Remove only the subnets that are not configured in the pairDevice.
2254 subnetsToBeRevoked = Sets.difference(subnetsToBeRevoked, subnetsExistingInPairDevice);
2255 }
2256
2257 if (!subnetsToBeRevoked.isEmpty()) {
2258 log.debug("Removing subnets for connectPoint: {}, subnets: {}", cp, subnetsToBeRevoked);
2259 defaultRoutingHandler.revokeSubnet(subnetsToBeRevoked);
2260 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002261
2262 // 2. Interface IP punts
2263 // Remove IP punts for old Intf address
2264 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2265 .map(InterfaceIpAddress::ipAddress)
2266 .collect(Collectors.toSet());
2267 ipAddressSet.stream()
2268 .map(InterfaceIpAddress::ipAddress)
2269 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2270 .forEach(interfaceIpAddress ->
2271 routingRulePopulator.revokeSingleIpPunts(
2272 cp.deviceId(), interfaceIpAddress));
2273
2274 // 3. Host unicast routing rule
2275 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002276 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002277 }
2278
2279 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2280 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2281 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2282
2283 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2284 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2285 .filter(intf -> !intf.connectPoint().equals(cp))
2286 .flatMap(intf -> intf.ipAddressesList().stream())
2287 .collect(Collectors.toSet());
2288 // 1. Partial subnet population
2289 // Add routing rules for newly added subnet, which does not also exist in
2290 // other interfaces in the same device
2291 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2292 .map(InterfaceIpAddress::subnetAddress)
2293 .collect(Collectors.toSet());
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002294 Set<IpPrefix> subnetsToBePopulated = ipPrefixSet.stream()
2295 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2296 .collect(Collectors.toSet());
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002297
Shibu Vijayakumar5e26f8c2020-01-07 11:45:09 +00002298 if (!subnetsToBePopulated.isEmpty()) {
2299 log.debug("Adding subnets for connectPoint: {}, subnets: {}", cp, subnetsToBePopulated);
2300
2301 // check if pair-device has the same subnet configured?
2302 Optional<DeviceId> pairDevice = getPairDeviceId(cp.deviceId());
2303 if (pairDevice.isPresent()) {
2304 Set<IpPrefix> pairDeviceIpPrefix = getDeviceSubnetMap().get(pairDevice.get());
2305
2306 Set<IpPrefix> subnetsToBePopulatedAsDualHomed = subnetsToBePopulated.stream()
2307 .filter(ipPrefix -> pairDeviceIpPrefix.contains(ipPrefix))
2308 .collect(Collectors.toSet());
2309 Set<IpPrefix> subnetsToBePopulatedAsSingleHomed = Sets.difference(subnetsToBePopulated,
2310 subnetsToBePopulatedAsDualHomed);
2311
2312 if (!subnetsToBePopulatedAsSingleHomed.isEmpty()) {
2313 defaultRoutingHandler.populateSubnet(
2314 Collections.singleton(cp),
2315 subnetsToBePopulatedAsSingleHomed);
2316 }
2317
2318 if (!subnetsToBePopulatedAsDualHomed.isEmpty()) {
2319 Set<ConnectPoint> cpts = new HashSet<>();
2320 cpts.add(cp);
2321 // As Subnets is DualHomed adding the pairDevice also as ConnectPoint.
2322 // PortNumber of connect point is not relevant in populate subnet and hence providing as ANY.
2323 ConnectPoint pairCp = new ConnectPoint(pairDevice.get(), PortNumber.ANY);
2324 cpts.add(pairCp);
2325
2326 log.debug("Adding DualHomed subnets for connectPoint: {} and its pair device: {}, subnets: {}",
2327 cp, pairCp, subnetsToBePopulatedAsDualHomed);
2328
2329 // populating the subnets as DualHomed
2330 defaultRoutingHandler.populateSubnet(
2331 cpts,
2332 subnetsToBePopulated);
2333
2334 // revoking the subnets populated in the device as it is now Dualhomed.
2335 defaultRoutingHandler.revokeSubnet(Collections.singleton(cp.deviceId()),
2336 subnetsToBePopulatedAsDualHomed);
2337 }
2338 } else {
2339 defaultRoutingHandler.populateSubnet(
2340 Collections.singleton(cp),
2341 subnetsToBePopulated);
2342 }
2343 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002344
2345 // 2. Interface IP punts
2346 // Add IP punts for new Intf address
2347 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2348 .map(InterfaceIpAddress::ipAddress)
2349 .collect(Collectors.toSet());
2350 ipAddressSet.stream()
2351 .map(InterfaceIpAddress::ipAddress)
2352 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2353 .forEach(interfaceIpAddress ->
2354 routingRulePopulator.populateSingleIpPunts(
2355 cp.deviceId(), interfaceIpAddress));
2356
2357 // 3. Host unicast routing rule
2358 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002359 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002360 }
sangho80f11cb2015-04-01 13:05:26 -07002361}