blob: 292c94172d19c586e9835c8cd8707b0419955758 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart61e24e12017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chanf0ae41e2017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
Charles Chan873661e2017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sangho80f11cb2015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070041import org.onosproject.cluster.ClusterEvent;
42import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010043import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070044import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020045import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.core.ApplicationId;
47import org.onosproject.core.CoreService;
48import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070049import org.onosproject.mastership.MastershipEvent;
50import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070051import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070052import org.onosproject.mcast.api.McastEvent;
53import org.onosproject.mcast.api.McastListener;
54import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080071import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070072import org.onosproject.net.device.DeviceEvent;
73import org.onosproject.net.device.DeviceListener;
74import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080075import org.onosproject.net.flow.TrafficSelector;
76import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070077import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080078import org.onosproject.net.host.HostEvent;
79import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070080import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080081import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070082import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020083import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070084import org.onosproject.net.intf.Interface;
85import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080086import org.onosproject.net.link.LinkEvent;
87import org.onosproject.net.link.LinkListener;
88import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070089import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080090import org.onosproject.net.packet.InboundPacket;
91import org.onosproject.net.packet.PacketContext;
92import org.onosproject.net.packet.PacketProcessor;
93import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010094import org.onosproject.net.topology.TopologyEvent;
95import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070096import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070097import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070098import org.onosproject.routeservice.RouteEvent;
99import org.onosproject.routeservice.RouteListener;
100import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -0700101import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
102import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -0800103import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -0700105import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -0700106import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700107import org.onosproject.segmentrouting.grouphandler.DestinationSet;
108import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi69f774d2018-02-28 12:10:50 +0100109import org.onosproject.segmentrouting.mcast.McastHandler;
110import org.onosproject.segmentrouting.mcast.McastRole;
Piere99511d2018-04-19 16:47:06 +0200111import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700112import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800116
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800117import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700118import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800119import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
121
Saurav Das261c3002017-06-13 15:35:54 -0700122import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700123import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Piere99511d2018-04-19 16:47:06 +0200124import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700125import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800126import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700127import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700128import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700129import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700130import org.onosproject.store.service.EventuallyConsistentMap;
131import org.onosproject.store.service.EventuallyConsistentMapBuilder;
132import org.onosproject.store.service.StorageService;
133import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800134import org.osgi.service.component.ComponentContext;
sangho80f11cb2015-04-01 13:05:26 -0700135import org.slf4j.Logger;
136import org.slf4j.LoggerFactory;
137
Saurav Das00e553b2018-04-21 17:19:48 -0700138import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700139import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800140import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800141import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800142import java.util.HashSet;
143import java.util.List;
144import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800145import java.util.Optional;
146import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200147import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800148import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200149import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan77cdde42018-05-08 21:35:50 -0700150import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800151import java.util.concurrent.Executors;
152import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800153import java.util.concurrent.TimeUnit;
154import java.util.concurrent.atomic.AtomicBoolean;
155import java.util.stream.Collectors;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700156import java.util.stream.IntStream;
sangho80f11cb2015-04-01 13:05:26 -0700157
Charles Chand6d25332016-02-26 22:19:52 -0800158import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800159import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700160import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800161import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
162import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chand6d25332016-02-26 22:19:52 -0800163
Charles Chanb7f75ac2016-01-11 18:28:54 -0800164/**
165 * Segment routing manager.
166 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700167@Service
168@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700169public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700170
Charles Chan46fdfaf2016-11-09 20:51:44 -0800171 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700172 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700173
174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700175 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700176
177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800178 private NeighbourResolutionService neighbourResolutionService;
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100181 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700182
183 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700184 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700185
186 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700187 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700188
189 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700190 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800191
192 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100193 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700194
195 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800196 DeviceAdminService deviceAdminService;
197
198 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800199 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700200
201 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100202 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700203
Charles Chan82ab1932016-01-30 23:22:37 -0800204 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800205 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700206
207 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800208 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700209
210 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100211 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700212
213 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan83163812018-01-09 13:45:07 -0800214 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700215
216 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700217 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800218
219 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800220 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800221
Saurav Dasc3604f12016-03-23 11:22:49 -0700222 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800223 public InterfaceService interfaceService;
224
Pier Luigi580fd8a2018-01-16 10:47:50 +0100225 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
226 public ClusterService clusterService;
227
228 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pierdb27b8d2018-04-17 16:29:56 +0200229 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100230
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700231 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
232 public LeadershipService leadershipService;
233
Charles Chan8d316332018-06-19 20:31:57 -0700234 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
235 public XconnectService xconnectService;
236
Charles Chan873661e2017-11-30 15:37:50 -0800237 @Property(name = "activeProbing", boolValue = true,
238 label = "Enable active probing to discover dual-homed hosts.")
239 boolean activeProbing = true;
240
Saurav Dasec683dc2018-04-27 18:42:30 -0700241 @Property(name = "singleHomedDown", boolValue = false,
242 label = "Enable administratively taking down single-homed hosts "
243 + "when all uplinks are gone")
244 boolean singleHomedDown = false;
245
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700246 @Property(name = "respondToUnknownHosts", boolValue = true,
247 label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
248 boolean respondToUnknownHosts = true;
249
Charles Chandebfea32016-10-24 14:52:01 -0700250 ArpHandler arpHandler = null;
251 IcmpHandler icmpHandler = null;
252 IpHandler ipHandler = null;
253 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700254 ApplicationId appId;
255 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700256
Charles Chandebfea32016-10-24 14:52:01 -0700257 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700258 private TunnelHandler tunnelHandler = null;
259 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700260 private InternalPacketProcessor processor = null;
261 private InternalLinkListener linkListener = null;
262 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700263 private AppConfigHandler appCfgHandler = null;
Pier Luigi69f774d2018-02-28 12:10:50 +0100264 public XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800265 McastHandler mcastHandler = null;
266 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800267 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800268 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800269 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800270 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100271 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800272 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700273 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
274 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700275 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100276 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700277 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700278 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200279 //Completable future for network configuration process to buffer config events handling during activation
280 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan39b75522018-04-21 00:44:29 -0700281 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700282
Charles Chan52003922018-04-05 16:31:15 -0700283 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700284 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700285
Charles Chanfbcb8812018-04-18 18:41:05 -0700286 // Handles host, route and mcast events respectively
287 private ScheduledExecutorService hostEventExecutor;
288 private ScheduledExecutorService routeEventExecutor;
289 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700290 private ExecutorService packetExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700291
292 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800293 /**
Saurav Das261c3002017-06-13 15:35:54 -0700294 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700295 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800296 */
Charles Chan873661e2017-11-30 15:37:50 -0800297 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700298 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800299 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700300 * Per device next objective ID store with (device id + vlanid) as key.
301 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800302 */
Charles Chan873661e2017-11-30 15:37:50 -0800303 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800304 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800305 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700306 * Per device next objective ID store with (device id + port + treatment + meta) as key.
307 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800308 */
Charles Chan873661e2017-11-30 15:37:50 -0800309 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800310 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800311
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700312 /**
313 * Per port dummy VLAN ID store with (connect point + ip address) as key.
314 * Used to keep track on dummy VLAN ID allocation.
315 */
316 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
317 dummyVlanIdStore = null;
318
Saurav Das2d94d312015-11-24 23:21:05 -0800319 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
320 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700321
Saurav Das261c3002017-06-13 15:35:54 -0700322 private AtomicBoolean programmingScheduled = new AtomicBoolean();
323
Charles Chanc91c8782016-03-30 17:54:24 -0700324 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700325 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
326 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700327 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700328 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800329 public SegmentRoutingDeviceConfig createConfig() {
330 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700331 }
332 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800333
Charles Chanc91c8782016-03-30 17:54:24 -0700334 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700335 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
336 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700337 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800338 @Override
339 public SegmentRoutingAppConfig createConfig() {
340 return new SegmentRoutingAppConfig();
341 }
342 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800343
Charles Chan82f19972016-05-17 13:13:55 -0700344 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
345 new ConfigFactory<ApplicationId, XConnectConfig>(
346 SubjectFactories.APP_SUBJECT_FACTORY,
347 XConnectConfig.class, "xconnect") {
348 @Override
349 public XConnectConfig createConfig() {
350 return new XConnectConfig();
351 }
352 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800353
Charles Chanc91c8782016-03-30 17:54:24 -0700354 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700355 new ConfigFactory<ApplicationId, McastConfig>(
356 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700357 McastConfig.class, "multicast") {
358 @Override
359 public McastConfig createConfig() {
360 return new McastConfig();
361 }
362 };
363
Charles Chan1963f4f2016-02-18 14:22:42 -0800364 /**
365 * Segment Routing App ID.
366 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800367 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chanb7f75ac2016-01-11 18:28:54 -0800368 /**
369 * The default VLAN ID assigned to the interfaces without subnet config.
370 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800371 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700372 /**
373 * The Vlan id used to transport pseudowire traffic across the network.
374 */
375 public static final VlanId PSEUDOWIRE_VLAN = VlanId.vlanId((short) 4093);
Saurav Das7c305372015-10-28 12:39:42 -0700376
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700377 /**
378 * Minumum and maximum value of dummy VLAN ID to be allocated.
379 */
380 public static final int MIN_DUMMY_VLAN_ID = 2;
381 public static final int MAX_DUMMY_VLAN_ID = 4093;
382
Saurav Dasec683dc2018-04-27 18:42:30 -0700383 Instant lastEdgePortEvent = Instant.EPOCH;
384
sangho80f11cb2015-04-01 13:05:26 -0700385 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800386 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800387 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700388
Charles Chanfbcb8812018-04-18 18:41:05 -0700389 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
390 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
391 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
392 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan77cdde42018-05-08 21:35:50 -0700393 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700394
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700395 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700396 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700397 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700398 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700399 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700400 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700401 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700402 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700403 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700404
Charles Chan10b0fb72017-02-02 16:20:42 -0800405 log.debug("Creating EC map vlannextobjectivestore");
406 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
407 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
408 vlanNextObjStore = vlanNextObjMapBuilder
409 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700410 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700411 .withTimestampProvider((k, v) -> new WallClockTimestamp())
412 .build();
413
Saurav Das2d94d312015-11-24 23:21:05 -0800414 log.debug("Creating EC map subnetnextobjectivestore");
415 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
416 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
417 portNextObjStore = portNextObjMapBuilder
418 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700419 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800420 .withTimestampProvider((k, v) -> new WallClockTimestamp())
421 .build();
422
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700423 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
424 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
425 dummyVlanIdStore = dummyVlanIdMapBuilder
426 .withName("dummyvlanidstore")
427 .withSerializer(createSerializer())
428 .withTimestampProvider((k, v) -> new WallClockTimestamp())
429 .build();
430
sangho4a5c42a2015-05-20 22:16:38 -0700431 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
432 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700433 tunnelStore = tunnelMapBuilder
434 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700435 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700436 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700437 .build();
438
439 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
440 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700441 policyStore = policyMapBuilder
442 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700443 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700444 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700445 .build();
446
Saurav Dasc3604f12016-03-23 11:22:49 -0700447 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800448 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700449 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800450 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800451 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
452 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700453 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800454 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700455 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800456 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800457 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
458 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800459 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
460 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700461 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700462 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700463 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
464 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800465 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
466 "staleLinkAge", "15000");
467 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
468 "allowDuplicateIps", "false");
Charles Chan873661e2017-11-30 15:37:50 -0800469 compCfgService.registerProperties(getClass());
470 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700471
Charles Chan2b078ae2015-10-14 11:24:40 -0700472 processor = new InternalPacketProcessor();
473 linkListener = new InternalLinkListener();
474 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700475 appCfgHandler = new AppConfigHandler(this);
476 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700477 mcastHandler = new McastHandler(this);
478 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800479 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700480 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800481 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800482 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigid8a15162018-02-15 16:33:08 +0100483 topologyHandler = new TopologyHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700484
Charles Chand6d25332016-02-26 22:19:52 -0800485 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700486 cfgService.registerConfigFactory(deviceConfigFactory);
487 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700488 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700489 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800490 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200491
Charles Chan6961f222018-01-04 14:26:07 -0800492 cfgListener.configureNetwork();
493
Charles Chan82ab1932016-01-30 23:22:37 -0800494 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700495 packetService.addProcessor(processor, PacketProcessor.director(2));
496 linkService.addListener(linkListener);
497 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700498 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700499 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100500 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700501 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700502 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700503
Charles Chanc12c3d02018-03-09 15:53:44 -0800504 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800505 l2TunnelHandler.init();
506
Andrea Campanella060cad82018-04-17 12:09:34 +0200507 networkConfigCompletion.whenComplete((value, ex) -> {
508 //setting to null for easier fall through
509 networkConfigCompletion = null;
510 //process all queued events
Charles Chan39b75522018-04-21 00:44:29 -0700511 queuedEvents.forEach(event -> {
Andrea Campanella060cad82018-04-17 12:09:34 +0200512 mainEventExecutor.execute(new InternalEventHandler(event));
513 });
514 });
515
sangho80f11cb2015-04-01 13:05:26 -0700516 log.info("Started");
517 }
518
Saurav Dase6c448a2018-01-18 12:07:33 -0800519 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700520 return new KryoNamespace.Builder()
521 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700522 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800523 VlanNextObjectiveStoreKey.class,
524 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700525 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800526 NextNeighbors.class,
527 Tunnel.class,
528 DefaultTunnel.class,
529 Policy.class,
530 TunnelPolicy.class,
531 Policy.Type.class,
532 PortNextObjectiveStoreKey.class,
533 XConnectStoreKey.class,
534 L2Tunnel.class,
535 L2TunnelPolicy.class,
536 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700537 DefaultL2TunnelPolicy.class,
538 DummyVlanIdStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700539 );
540 }
541
sangho80f11cb2015-04-01 13:05:26 -0700542 @Deactivate
543 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700544 mainEventExecutor.shutdown();
545 hostEventExecutor.shutdown();
546 routeEventExecutor.shutdown();
547 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700548 packetExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700549
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700550 mainEventExecutor = null;
551 hostEventExecutor = null;
552 routeEventExecutor = null;
553 mcastEventExecutor = null;
554 packetExecutor = null;
555
Charles Chan72f556a2015-10-05 17:50:33 -0700556 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700557 cfgService.unregisterConfigFactory(deviceConfigFactory);
558 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700559 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700560 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800561 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700562
Charles Chanfd48c222017-06-19 00:43:31 -0700563 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700564 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700565 linkService.removeListener(linkListener);
566 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700567 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700568 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100569 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700570 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700571 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700572
Charles Chan2e71ef32017-02-23 15:44:08 -0800573 neighbourResolutionService.unregisterNeighbourHandlers(appId);
574
sangho80f11cb2015-04-01 13:05:26 -0700575 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700576 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700577 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700578 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700579 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700580 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700581
Saurav Das261c3002017-06-13 15:35:54 -0700582 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800583 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700584 portNextObjStore.destroy();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700585 dummyVlanIdStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700586 tunnelStore.destroy();
587 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100588
589 mcastHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700590 log.info("Stopped");
591 }
592
Charles Chan873661e2017-11-30 15:37:50 -0800593 @Modified
594 private void modified(ComponentContext context) {
595 Dictionary<?, ?> properties = context.getProperties();
596 if (properties == null) {
597 return;
598 }
599
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700600 String strActiveProbing = Tools.get(properties, "activeProbing");
601 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800602 if (expectActiveProbing != activeProbing) {
603 activeProbing = expectActiveProbing;
604 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
605 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700606
607 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
608 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
609 if (expectSingleHomedDown != singleHomedDown) {
610 singleHomedDown = expectSingleHomedDown;
611 log.info("{} downing of single homed hosts for lost uplinks",
612 singleHomedDown ? "Enabling" : "Disabling");
613 if (singleHomedDown && linkHandler != null) {
614 hostService.getHosts().forEach(host -> host.locations()
615 .forEach(loc -> {
616 if (interfaceService.isConfigured(loc)) {
617 linkHandler.checkUplinksForHost(loc);
618 }
619 }));
620 } else {
621 log.warn("Disabling singleHomedDown does not re-enable already "
622 + "downed ports for single-homed hosts");
623 }
624 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700625
626 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
627 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
628 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
629 respondToUnknownHosts = expectRespondToUnknownHosts;
630 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
631 }
Charles Chan873661e2017-11-30 15:37:50 -0800632 }
633
sangho27462c62015-05-14 00:39:53 -0700634 @Override
635 public List<Tunnel> getTunnels() {
636 return tunnelHandler.getTunnels();
637 }
638
639 @Override
sanghobd812f82015-06-29 14:58:47 -0700640 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
641 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700642 }
643
644 @Override
sanghobd812f82015-06-29 14:58:47 -0700645 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700646 for (Policy policy: policyHandler.getPolicies()) {
647 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
648 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
649 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
650 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700651 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700652 }
653 }
654 }
sanghobd812f82015-06-29 14:58:47 -0700655 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700656 }
657
658 @Override
sanghobd812f82015-06-29 14:58:47 -0700659 public PolicyHandler.Result removePolicy(Policy policy) {
660 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700661 }
662
663 @Override
sanghobd812f82015-06-29 14:58:47 -0700664 public PolicyHandler.Result createPolicy(Policy policy) {
665 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700666 }
667
668 @Override
669 public List<Policy> getPolicies() {
670 return policyHandler.getPolicies();
671 }
672
Saurav Das07c74602016-04-27 18:35:50 -0700673 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700674 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
675 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700676 }
677
678 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800679 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700680 return l2TunnelHandler.getL2Tunnels();
681 }
682
683 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800684 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700685 return l2TunnelHandler.getL2Policies();
686 }
687
Saurav Dasdebcf882018-04-06 20:16:01 -0700688 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700689 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700690 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
691
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700692 // get both added and pending pseudowires
693 List<L2TunnelDescription> pseudowires = new ArrayList<>();
694 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
695 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700696 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700697
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700698 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
699
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700700 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
701 L2TunnelHandler.Result res;
702 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
703 res = addPseudowire(pw);
704 if (res != L2TunnelHandler.Result.SUCCESS) {
705 log.error("Pseudowire with id {} can not be instantiated !", res);
706 retRes = res;
707 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700708 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700709
710 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700711 }
712
713 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800714 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700715 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700716 }
717
718 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800719 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700720 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700721 }
722
723 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700724 public void rerouteNetwork() {
725 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700726 }
727
Charles Chand7844e52016-10-20 17:02:44 -0700728 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800729 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
730 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800731 deviceConfiguration.getRouters().forEach(device ->
732 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700733 return deviceSubnetMap;
734 }
735
Saurav Das62ae6792017-05-15 15:34:25 -0700736
737 @Override
738 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
739 if (defaultRoutingHandler != null) {
740 return defaultRoutingHandler.getCurrentEmcpSpgMap();
741 } else {
742 return null;
743 }
744 }
745
746 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700747 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
748 if (dsNextObjStore != null) {
749 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700750 } else {
751 return ImmutableMap.of();
752 }
753 }
754
Saurav Dasfbe74572017-08-03 18:30:35 -0700755 @Override
756 public void verifyGroups(DeviceId id) {
757 DefaultGroupHandler gh = groupHandlerMap.get(id);
758 if (gh != null) {
759 gh.triggerBucketCorrector();
760 }
761 }
762
Saurav Das6430f412018-01-25 09:49:01 -0800763 @Override
764 public ImmutableMap<Link, Boolean> getSeenLinks() {
765 return linkHandler.getSeenLinks();
766 }
767
768 @Override
769 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
770 return linkHandler.getDownedPorts();
771 }
772
Pier Luigi0f9635b2018-01-15 18:06:43 +0100773 @Override
774 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
775 return mcastHandler.getMcastNextIds(mcastIp);
776 }
777
778 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +0100779 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +0100780 return mcastHandler.getMcastRoles(mcastIp);
781 }
782
783 @Override
Piere99511d2018-04-19 16:47:06 +0200784 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
785 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
786 }
787
788 @Override
Pier Luigi0f9635b2018-01-15 18:06:43 +0100789 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
790 return mcastHandler.getMcastPaths(mcastIp);
791 }
792
Pierdb27b8d2018-04-17 16:29:56 +0200793 @Override
Pier71c55772018-04-17 17:25:22 +0200794 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
795 ConnectPoint sourcecp) {
796 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
797 }
798
799 @Override
Pierdb27b8d2018-04-17 16:29:56 +0200800 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
801 return mcastHandler.getMcastLeaders(mcastIp);
802 }
803
Charles Chanb13e0702018-04-17 18:56:53 -0700804 @Override
805 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
806 return defaultRoutingHandler == null ? ImmutableMap.of() :
807 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
808 }
809
810 @Override
811 public Map<DeviceId, Boolean> getShouldProgramCache() {
812 return defaultRoutingHandler == null ? ImmutableMap.of() :
813 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
814 }
815
Charles Chan8d316332018-06-19 20:31:57 -0700816 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -0700817 public ApplicationId appId() {
818 return appId;
819 }
820
821 /**
822 * Returns the device configuration.
823 *
824 * @return device configuration
825 */
826 public DeviceConfiguration deviceConfiguration() {
827 return deviceConfiguration;
828 }
829
830 /**
Saurav Das261c3002017-06-13 15:35:54 -0700831 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700832 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700833 *
834 * @return next objective ID store
835 */
Saurav Das261c3002017-06-13 15:35:54 -0700836 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
837 dsNextObjStore() {
838 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700839 }
840
841 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700842 * Per device next objective ID store with (device id + vlanid) as key.
843 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700844 *
845 * @return vlan next object store
846 */
847 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
848 return vlanNextObjStore;
849 }
850
851 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700852 * Per device next objective ID store with (device id + port + treatment + meta) as key.
853 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700854 *
855 * @return port next object store.
856 */
857 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
858 return portNextObjStore;
859 }
860
861 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700862 * Per port dummy VLAN ID store with (connect point + ip address) as key.
863 * Used to keep track on dummy VLAN ID allocation.
864 *
865 * @return dummy vlan id store.
866 */
867 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
868 return dummyVlanIdStore;
869 }
870
871 /**
Saurav Das261c3002017-06-13 15:35:54 -0700872 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
873 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700874 *
875 * @return MPLS-ECMP value
876 */
877 public boolean getMplsEcmp() {
878 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
879 .getConfig(this.appId, SegmentRoutingAppConfig.class);
880 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
881 }
882
883 /**
sangho80f1f892015-05-19 11:57:42 -0700884 * Returns the tunnel object with the tunnel ID.
885 *
886 * @param tunnelId Tunnel ID
887 * @return Tunnel reference
888 */
sangho27462c62015-05-14 00:39:53 -0700889 public Tunnel getTunnel(String tunnelId) {
890 return tunnelHandler.getTunnel(tunnelId);
891 }
892
Charles Chan8d316332018-06-19 20:31:57 -0700893 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +0100894 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -0700895 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
896 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -0700897 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
898 }
899
Charles Chan8d316332018-06-19 20:31:57 -0700900 @Override
901 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -0700902 SegmentRoutingDeviceConfig deviceConfig =
903 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
904 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
905 }
Charles Chan8d316332018-06-19 20:31:57 -0700906
907 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -0700908 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -0700909 SegmentRoutingDeviceConfig deviceConfig =
910 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
911 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
912 }
913
914 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700915 * Returns locations of given resolved route.
916 *
917 * @param resolvedRoute resolved route
918 * @return locations of nexthop. Might be empty if next hop is not found
919 */
920 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
921 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
922 return Optional.ofNullable(hostService.getHost(hostId))
923 .map(Host::locations).orElse(Sets.newHashSet())
924 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
925 }
926
927 /**
Charles Chan90772a72017-02-08 15:52:08 -0800928 * Returns vlan port map of given device.
929 *
930 * @param deviceId device id
931 * @return vlan-port multimap
932 */
933 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
934 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
935
936 interfaceService.getInterfaces().stream()
937 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
938 .forEach(intf -> {
939 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700940 intf.vlanTagged().forEach(vlanTagged ->
941 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
942 );
Charles Chan90772a72017-02-08 15:52:08 -0800943 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
944 });
945 vlanPortMap.removeAll(VlanId.NONE);
946
947 return vlanPortMap;
948 }
949
950 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800951 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800952 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700953 *
954 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800955 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800956 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700957 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700958 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700959 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800960 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
961 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700962 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800963 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800964 + "device {} not found", deviceId);
965 return -1;
966 }
967 }
968
969 /**
970 * Returns the next objective ID for the given portNumber, given the treatment.
971 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700972 * would result in different objectives. If the next object does not exist,
973 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800974 *
975 * @param deviceId Device ID
976 * @param portNum port number on device for which NextObjective is queried
977 * @param treatment the actions to apply on the packets (should include outport)
978 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700979 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700980 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800981 */
982 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
983 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700984 TrafficSelector meta,
985 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800986 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
987 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700988 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800989 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800990 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
991 + " not found", deviceId);
992 return -1;
993 }
994 }
995
Saurav Das62ae6792017-05-15 15:34:25 -0700996 /**
997 * Returns the group handler object for the specified device id.
998 *
999 * @param devId the device identifier
1000 * @return the groupHandler object for the device id, or null if not found
1001 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001002 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001003 return groupHandlerMap.get(devId);
1004 }
1005
1006 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001007 * Returns the default routing handler object.
1008 *
1009 * @return the default routing handler object
1010 */
1011 public DefaultRoutingHandler getRoutingHandler() {
1012 return defaultRoutingHandler;
1013 }
1014
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001015 /**
1016 * Returns new dummy VLAN ID.
1017 * Dummy VLAN ID should be unique in each connect point.
1018 *
1019 * @param cp connect point
1020 * @param ipAddress IP address
1021 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1022 */
1023 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1024 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1025 dummyVlanIdStore.entrySet().stream().filter(entry ->
1026 (entry.getKey()).connectPoint().equals(cp))
1027 .map(Map.Entry::getValue)
1028 .collect(Collectors.toSet()));
1029
1030 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1031 i -> VlanId.vlanId((short) (i & 0xFFFF))
1032 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1033
1034 if (!dummyVlanId.equals(VlanId.NONE)) {
1035 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1036 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1037 } else {
1038 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1039 }
1040 return dummyVlanId;
1041 }
1042
1043
sangho80f11cb2015-04-01 13:05:26 -07001044 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001045 @Override
1046 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001047 packetExecutor.execute(() -> processPacketInternal(context));
1048 }
sangho80f11cb2015-04-01 13:05:26 -07001049
Charles Chan77cdde42018-05-08 21:35:50 -07001050 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001051 if (context.isHandled()) {
1052 return;
1053 }
1054
1055 InboundPacket pkt = context.inPacket();
1056 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001057
1058 if (ethernet == null) {
1059 return;
1060 }
1061
Saurav Das261c3002017-06-13 15:35:54 -07001062 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1063 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001064 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001065 log.warn("Received unexpected ARP packet on {}",
1066 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001067 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001068 return;
sangho80f11cb2015-04-01 13:05:26 -07001069 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001070 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1071 //ipHandler.addToPacketBuffer(ipv4Packet);
1072 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1073 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001074 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001075 // NOTE: We don't support IP learning at this moment so this
1076 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001077 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001078 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001079 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1080 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001081 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001082 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001083 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1084 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1085 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1086 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1087 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1088 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001089 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001090 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001091 }
1092 } else {
1093 // NOTE: We don't support IP learning at this moment so this
1094 // is not necessary. Also it causes duplication of DHCPv6 packets.
1095 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1096 }
sangho80f11cb2015-04-01 13:05:26 -07001097 }
1098 }
1099 }
1100
sangho80f11cb2015-04-01 13:05:26 -07001101 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001102 private Event event;
1103
1104 InternalEventHandler(Event event) {
1105 this.event = event;
1106 }
1107
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001108 @Override
sangho80f11cb2015-04-01 13:05:26 -07001109 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001110 try {
1111 // TODO We should also change SR routing and PW to listen to TopologyEvents
1112 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1113 event.type() == LinkEvent.Type.LINK_UPDATED) {
1114 linkHandler.processLinkAdded((Link) event.subject());
1115 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1116 linkHandler.processLinkRemoved((Link) event.subject());
1117 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1118 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1119 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1120 DeviceId deviceId = ((Device) event.subject()).id();
1121 if (deviceService.isAvailable(deviceId)) {
1122 log.info("** DEVICE UP Processing device event {} "
1123 + "for available device {}",
1124 event.type(), ((Device) event.subject()).id());
1125 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001126 } else {
Charles Chan52003922018-04-05 16:31:15 -07001127 log.info(" ** DEVICE DOWN Processing device event {}"
1128 + " for unavailable device {}",
1129 event.type(), ((Device) event.subject()).id());
1130 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001131 }
Charles Chan52003922018-04-05 16:31:15 -07001132 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1133 // typically these calls come when device is added first time
1134 // so port filtering rules are handled at the device_added event.
1135 // port added calls represent all ports on the device,
1136 // enabled or not.
1137 log.trace("** PORT ADDED {}/{} -> {}",
1138 ((DeviceEvent) event).subject().id(),
1139 ((DeviceEvent) event).port().number(),
1140 event.type());
1141 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1142 // these calls happen for every subsequent event
1143 // ports enabled, disabled, switch goes away, comes back
1144 log.info("** PORT UPDATED {}/{} -> {}",
1145 event.subject(),
1146 ((DeviceEvent) event).port(),
1147 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001148 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001149 ((DeviceEvent) event).port());
1150 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1151 // Process topology event, needed for all modules relying on
1152 // topology service for path computation
1153 TopologyEvent topologyEvent = (TopologyEvent) event;
1154 log.info("Processing topology event {}, topology age {}, reasons {}",
1155 event.type(), topologyEvent.subject().time(),
1156 topologyEvent.reasons().size());
1157 topologyHandler.processTopologyChange(topologyEvent.reasons());
1158 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1159 hostHandler.processHostAddedEvent((HostEvent) event);
1160 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1161 hostHandler.processHostMovedEvent((HostEvent) event);
1162 routeHandler.processHostMovedEvent((HostEvent) event);
1163 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1164 hostHandler.processHostRemovedEvent((HostEvent) event);
1165 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1166 hostHandler.processHostUpdatedEvent((HostEvent) event);
1167 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1168 routeHandler.processRouteAdded((RouteEvent) event);
1169 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1170 routeHandler.processRouteUpdated((RouteEvent) event);
1171 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1172 routeHandler.processRouteRemoved((RouteEvent) event);
1173 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1174 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1175 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1176 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1177 event.type() == McastEvent.Type.SINKS_ADDED ||
1178 event.type() == McastEvent.Type.SINKS_REMOVED ||
1179 event.type() == McastEvent.Type.ROUTE_ADDED ||
1180 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1181 mcastHandler.processMcastEvent((McastEvent) event);
1182 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1183 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1184 Class configClass = netcfgEvent.configClass();
1185 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1186 appCfgHandler.processAppConfigAdded(netcfgEvent);
1187 log.info("App config event .. configuring network");
1188 cfgListener.configureNetwork();
1189 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1190 log.info("Segment Routing Device Config added for {}", event.subject());
1191 cfgListener.configureNetwork();
1192 } else if (configClass.equals(XConnectConfig.class)) {
1193 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1194 } else if (configClass.equals(InterfaceConfig.class)) {
1195 log.info("Interface Config added for {}", event.subject());
1196 cfgListener.configureNetwork();
1197 } else {
1198 log.error("Unhandled config class: {}", configClass);
1199 }
1200 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1201 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1202 Class configClass = netcfgEvent.configClass();
1203 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1204 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1205 log.info("App config event .. configuring network");
1206 cfgListener.configureNetwork();
1207 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1208 log.info("Segment Routing Device Config updated for {}", event.subject());
1209 createOrUpdateDeviceConfiguration();
1210 } else if (configClass.equals(XConnectConfig.class)) {
1211 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1212 } else if (configClass.equals(InterfaceConfig.class)) {
1213 log.info("Interface Config updated for {}", event.subject());
1214 createOrUpdateDeviceConfiguration();
1215 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1216 (InterfaceConfig) netcfgEvent.prevConfig().get());
1217 } else {
1218 log.error("Unhandled config class: {}", configClass);
1219 }
1220 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1221 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1222 Class configClass = netcfgEvent.configClass();
1223 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1224 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1225 log.info("App config event .. configuring network");
1226 cfgListener.configureNetwork();
1227 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1228 // TODO Handle sr device config removal
1229 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1230 } else if (configClass.equals(XConnectConfig.class)) {
1231 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1232 } else if (configClass.equals(InterfaceConfig.class)) {
1233 // TODO Handle interface removal
1234 log.info("InterfaceConfig removal is not handled in current implementation");
1235 } else {
1236 log.error("Unhandled config class: {}", configClass);
1237 }
Saurav Das00e553b2018-04-21 17:19:48 -07001238 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1239 MastershipEvent me = (MastershipEvent) event;
1240 DeviceId deviceId = me.subject();
1241 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1242 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1243 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1244 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1245 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1246 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan52003922018-04-05 16:31:15 -07001247 } else {
1248 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001249 }
Charles Chan52003922018-04-05 16:31:15 -07001250 } catch (Exception e) {
1251 log.error("SegmentRouting event handler thread thrown an exception: {}",
1252 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001253 }
sangho80f11cb2015-04-01 13:05:26 -07001254 }
1255 }
1256
Saurav Dase6c448a2018-01-18 12:07:33 -08001257 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001258 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001259
1260 // NOTE: Punt ARP/NDP even when the device is not configured.
1261 // Host learning without network config is required for CORD config generator.
1262 routingRulePopulator.populateIpPunts(device.id());
1263 routingRulePopulator.populateArpNdpPunts(device.id());
1264
Charles Chan319d1a22015-11-03 10:42:14 -08001265 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001266 log.warn("Device configuration unavailable. Device {} will be "
1267 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001268 return;
1269 }
Charles Chan72779502016-04-23 17:36:10 -07001270 processDeviceAddedInternal(device.id());
1271 }
1272
1273 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001274 // Irrespective of whether the local is a MASTER or not for this device,
1275 // we need to create a SR-group-handler instance. This is because in a
1276 // multi-instance setup, any instance can initiate forwarding/next-objectives
1277 // for any switch (even if this instance is a SLAVE or not even connected
1278 // to the switch). To handle this, a default-group-handler instance is necessary
1279 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001280 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1281 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001282 DefaultGroupHandler groupHandler;
1283 try {
1284 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001285 createGroupHandler(deviceId,
1286 appId,
1287 deviceConfiguration,
1288 linkService,
1289 flowObjectiveService,
1290 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001291 } catch (DeviceConfigNotFoundException e) {
1292 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1293 return;
1294 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001295 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001296 deviceId);
1297 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001298 }
Saurav Dasb149be12016-06-07 10:08:06 -07001299
Charles Chan72779502016-04-23 17:36:10 -07001300 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001301 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001302 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001303 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001304 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001305 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001306 }
Charles Chan82ab1932016-01-30 23:22:37 -08001307
Charles Chandebfea32016-10-24 14:52:01 -07001308 appCfgHandler.init(deviceId);
Charles Chan074fae62018-04-29 18:11:37 -07001309 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1310 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sangho80f11cb2015-04-01 13:05:26 -07001311 }
1312
Saurav Dasc3604f12016-03-23 11:22:49 -07001313 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001314 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001315 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001316 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001317 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001318 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001319 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001320 portNextObjStore.entrySet().stream()
1321 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001322 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001323 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001324
Saurav Dasfbe74572017-08-03 18:30:35 -07001325 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1326 if (gh != null) {
1327 gh.shutdown();
1328 }
Saurav Das62ae6792017-05-15 15:34:25 -07001329 // Note that a switch going down is associated with all of its links
1330 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001331 // while the link-downs are ignored. We cannot rely on the ordering of
1332 // events - i.e we cannot expect all link-downs to come before the
1333 // switch down - so we purge all seen-links for the switch before
1334 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001335 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001336 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001337 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001338 xConnectHandler.removeDevice(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001339
1340 // Cleanup all internal groupHandler stores for this device. Should be
1341 // done after all rerouting or rehashing has been completed
1342 groupHandlerMap.entrySet()
1343 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001344 }
1345
Saurav Das49368392018-04-23 18:42:12 -07001346 /**
1347 * Purge the destinationSet nextObjective store of entries with this device
1348 * as key. Erases app-level knowledge of hashed groups in this device.
1349 *
1350 * @param devId the device identifier
1351 */
Saurav Das00e553b2018-04-21 17:19:48 -07001352 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001353 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001354 dsNextObjStore.entrySet().stream()
1355 .filter(entry -> entry.getKey().deviceId().equals(devId))
1356 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1357 }
1358
Saurav Dasec683dc2018-04-27 18:42:30 -07001359 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001360 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1361 log.warn("Device configuration uploading. Not handling port event for"
1362 + "dev: {} port: {}", device.id(), port.number());
1363 return;
1364 }
Saurav Dasf9332192017-02-18 14:05:44 -08001365
Saurav Dasec683dc2018-04-27 18:42:30 -07001366 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1367 lastEdgePortEvent = Instant.now();
1368 }
1369
Saurav Dasf9332192017-02-18 14:05:44 -08001370 if (!mastershipService.isLocalMaster(device.id())) {
1371 log.debug("Not master for dev:{} .. not handling port updated event"
1372 + "for port {}", device.id(), port.number());
1373 return;
1374 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001375 processPortUpdated(device.id(), port);
1376 }
Saurav Dasf9332192017-02-18 14:05:44 -08001377
Saurav Dasec683dc2018-04-27 18:42:30 -07001378 /**
1379 * Adds or remove filtering rules for the given switchport. If switchport is
1380 * an edge facing port, additionally handles host probing and broadcast
1381 * rules. Must be called by local master of device.
1382 *
1383 * @param deviceId the device identifier
1384 * @param port the port to update
1385 */
1386 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001387 // first we handle filtering rules associated with the port
1388 if (port.isEnabled()) {
1389 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001390 deviceId, port.number());
1391 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001392 } else {
1393 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001394 deviceId, port.number());
1395 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001396 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001397
1398 // portUpdated calls are for ports that have gone down or up. For switch
1399 // to switch ports, link-events should take care of any re-routing or
1400 // group editing necessary for port up/down. Here we only process edge ports
1401 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001402 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001403 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1404 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1405 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001406
Saurav Das3fb28272017-03-04 16:08:47 -08001407 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001408 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001409 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001410 return;
1411 }
Saurav Das3fb28272017-03-04 16:08:47 -08001412 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001413 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001414 }
1415 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001416 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001417 }
1418 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001419 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001420 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001421 }
1422
Saurav Dasec683dc2018-04-27 18:42:30 -07001423 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001424 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001425 boolean portUp = port.isEnabled();
1426 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001427 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001428 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001429 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001430 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001431 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001432 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001433 }
1434
Saurav Dasec683dc2018-04-27 18:42:30 -07001435 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001436 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001437 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001438 } else {
1439 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001440 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001441 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001442 }
1443 }
sangho27462c62015-05-14 00:39:53 -07001444
Charles Chan8ca5a122017-10-20 16:06:55 -07001445 private void createOrUpdateDeviceConfiguration() {
1446 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001447 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001448 deviceConfiguration = new DeviceConfiguration(this);
1449 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001450 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001451 deviceConfiguration.updateConfig();
1452 }
1453 }
1454
Charles Chanfbcb8812018-04-18 18:41:05 -07001455 private void createOrUpdateDefaultRoutingHandler() {
1456 if (defaultRoutingHandler == null) {
1457 log.info("Creating new DefaultRoutingHandler");
1458 defaultRoutingHandler = new DefaultRoutingHandler(this);
1459 } else {
1460 log.info("Updating DefaultRoutingHandler");
1461 defaultRoutingHandler.update(this);
1462 }
1463 }
1464
Pier Ventreb6a7f342016-11-26 21:05:22 -08001465 /**
1466 * Registers the given connect point with the NRS, this is necessary
1467 * to receive the NDP and ARP packets from the NRS.
1468 *
1469 * @param portToRegister connect point to register
1470 */
1471 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001472 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001473 portToRegister,
1474 neighbourHandler,
1475 appId
1476 );
1477 }
1478
Charles Chan72f556a2015-10-05 17:50:33 -07001479 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001480 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001481 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001482
Charles Chanb7f75ac2016-01-11 18:28:54 -08001483 /**
1484 * Constructs the internal network config listener.
1485 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001486 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001487 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001488 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001489 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001490 }
1491
Charles Chanb7f75ac2016-01-11 18:28:54 -08001492 /**
1493 * Reads network config and initializes related data structure accordingly.
1494 */
Charles Chan873661e2017-11-30 15:37:50 -08001495 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001496 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001497
1498 // Setting handling of network configuration events completable future
1499 // The completable future is needed because of the async behaviour of the configureNetwork,
1500 // listener registration and event arrival
1501 // Enables us to buffer the events and execute them when the configure network is done.
1502 networkConfigCompletion = new CompletableFuture<>();
1503
1504 // add a small delay to absorb multiple network config added notifications
1505 if (!programmingScheduled.get()) {
1506 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1507 programmingScheduled.set(true);
1508 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1509 }
1510
Charles Chan8ca5a122017-10-20 16:06:55 -07001511 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001512
Charles Chan46fdfaf2016-11-09 20:51:44 -08001513 arpHandler = new ArpHandler(srManager);
1514 icmpHandler = new IcmpHandler(srManager);
1515 ipHandler = new IpHandler(srManager);
1516 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chanfbcb8812018-04-18 18:41:05 -07001517 createOrUpdateDefaultRoutingHandler();
Charles Chane7c61022015-10-07 14:21:45 -07001518
1519 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1520 groupHandlerMap, tunnelStore);
1521 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1522 flowObjectiveService,
1523 tunnelHandler, policyStore);
Andrea Campanella060cad82018-04-17 12:09:34 +02001524 networkConfigCompletion.complete(true);
1525
Charles Chan72779502016-04-23 17:36:10 -07001526 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001527
Charles Chane7c61022015-10-07 14:21:45 -07001528 }
1529
Charles Chan72f556a2015-10-05 17:50:33 -07001530 @Override
1531 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001532 if (mainEventExecutor == null) {
1533 return;
1534 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001535 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1536 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1537 switch (event.type()) {
1538 case CONFIG_ADDED:
1539 case CONFIG_UPDATED:
1540 case CONFIG_REMOVED:
1541 log.trace("Schedule Network Config event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001542 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1543 mainEventExecutor.execute(new InternalEventHandler(event));
1544 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001545 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001546 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001547 break;
1548 default:
1549 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001550 }
1551 }
Saurav Das261c3002017-06-13 15:35:54 -07001552
Charles Chanc4a68c32018-01-03 16:26:32 -08001553 @Override
1554 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001555 if (event.type() == CONFIG_REGISTERED ||
1556 event.type() == CONFIG_UNREGISTERED) {
1557 log.debug("Ignore event {} due to type mismatch", event);
1558 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001559 }
Saurav Dase321cff2018-02-09 17:26:45 -08001560
1561 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1562 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1563 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -08001564 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001565 log.debug("Ignore event {} due to class mismatch", event);
1566 return false;
1567 }
1568
1569 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001570 }
1571
Saurav Das261c3002017-06-13 15:35:54 -07001572 private final class ConfigChange implements Runnable {
1573 @Override
1574 public void run() {
1575 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001576 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001577 for (Device device : deviceService.getDevices()) {
1578 processDeviceAdded(device);
1579 }
1580 defaultRoutingHandler.startPopulationProcess();
1581 }
1582 }
Charles Chan72f556a2015-10-05 17:50:33 -07001583 }
Charles Chanf4586112015-11-09 16:37:23 -08001584
Charles Chan3f4aca62018-03-21 16:57:47 -07001585 private class InternalLinkListener implements LinkListener {
1586 @Override
1587 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001588 if (mainEventExecutor == null) {
1589 return;
1590 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001591 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1592 event.type() == LinkEvent.Type.LINK_UPDATED ||
1593 event.type() == LinkEvent.Type.LINK_REMOVED) {
1594 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001595 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1596 mainEventExecutor.execute(new InternalEventHandler(event));
1597 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001598 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001599 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001600 }
1601 }
1602 }
1603
1604 private class InternalDeviceListener implements DeviceListener {
1605 @Override
1606 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001607 if (mainEventExecutor == null) {
1608 return;
1609 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001610 switch (event.type()) {
1611 case DEVICE_ADDED:
1612 case PORT_UPDATED:
1613 case PORT_ADDED:
1614 case DEVICE_UPDATED:
1615 case DEVICE_AVAILABILITY_CHANGED:
1616 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001617 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1618 mainEventExecutor.execute(new InternalEventHandler(event));
1619 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001620 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001621 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001622 break;
1623 default:
1624 }
1625 }
1626 }
1627
1628 private class InternalTopologyListener implements TopologyListener {
1629 @Override
1630 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001631 if (mainEventExecutor == null) {
1632 return;
1633 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001634 switch (event.type()) {
1635 case TOPOLOGY_CHANGED:
1636 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001637 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1638 mainEventExecutor.execute(new InternalEventHandler(event));
1639 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001640 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001641 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001642 break;
1643 default:
1644 }
1645 }
1646 }
1647
Charles Chanf4586112015-11-09 16:37:23 -08001648 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001649 @Override
1650 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001651 if (hostEventExecutor == null) {
1652 return;
1653 }
Charles Chanf4586112015-11-09 16:37:23 -08001654 switch (event.type()) {
1655 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001656 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001657 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001658 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001659 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001660 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08001661 break;
1662 default:
1663 log.warn("Unsupported host event type: {}", event.type());
1664 break;
1665 }
1666 }
1667 }
1668
Charles Chanc91c8782016-03-30 17:54:24 -07001669 private class InternalMcastListener implements McastListener {
1670 @Override
1671 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001672 if (mcastEventExecutor == null) {
1673 return;
1674 }
Charles Chanc91c8782016-03-30 17:54:24 -07001675 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07001676 case SOURCES_ADDED:
1677 case SOURCES_REMOVED:
1678 case SINKS_ADDED:
1679 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07001680 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02001681 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001682 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001683 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01001684 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001685 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001686 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07001687 break;
1688 }
1689 }
1690 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001691
Charles Chandebfea32016-10-24 14:52:01 -07001692 private class InternalRouteEventListener implements RouteListener {
1693 @Override
1694 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001695 if (routeEventExecutor == null) {
1696 return;
1697 }
Charles Chandebfea32016-10-24 14:52:01 -07001698 switch (event.type()) {
1699 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07001700 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07001701 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07001702 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001703 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001704 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07001705 break;
Charles Chandebfea32016-10-24 14:52:01 -07001706 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001707 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07001708 break;
1709 }
1710 }
1711 }
Saurav Das62ae6792017-05-15 15:34:25 -07001712
Charles Chanfbcb8812018-04-18 18:41:05 -07001713 private class InternalMastershipListener implements MastershipListener {
1714 @Override
1715 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001716 if (mainEventExecutor == null) {
1717 return;
1718 }
Charles Chanfbcb8812018-04-18 18:41:05 -07001719 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07001720 case MASTER_CHANGED:
1721 log.debug("Mastership event: {}/{}", event.subject(),
1722 event.roleInfo());
1723 mainEventExecutor.execute(new InternalEventHandler(event));
1724 break;
1725 case BACKUPS_CHANGED:
1726 case SUSPENDED:
1727 default:
1728 log.debug("Mastership event type {} not handled", event.type());
1729 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07001730 }
1731 }
1732 }
1733
Saurav Das00e553b2018-04-21 17:19:48 -07001734 class InternalClusterListener implements ClusterEventListener {
1735 private Instant lastClusterEvent = Instant.EPOCH;
1736
1737 long timeSinceLastClusterEvent() {
1738 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1739 }
1740
1741 @Override
1742 public void event(ClusterEvent event) {
1743 switch (event.type()) {
1744 case INSTANCE_ACTIVATED:
1745 case INSTANCE_ADDED:
1746 case INSTANCE_READY:
1747 log.debug("Cluster event {} ignored", event.type());
1748 break;
1749 case INSTANCE_DEACTIVATED:
1750 case INSTANCE_REMOVED:
1751 log.info("** Cluster event {}", event.type());
1752 lastClusterEvent = Instant.now();
1753 break;
1754 default:
1755 break;
1756 }
1757
1758 }
1759
1760 }
1761
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001762 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1763 try {
1764 Set<Interface> intfs = conf.getInterfaces();
1765 Set<Interface> prevIntfs = prevConf.getInterfaces();
1766
1767 // Now we only handle one interface config at each port.
1768 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1769 log.warn("Interface update aborted - one at a time is allowed, " +
1770 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1771 return;
1772 }
1773
Andrea Campanella060cad82018-04-17 12:09:34 +02001774 //The system is in an incoherent state, abort
1775 if (defaultRoutingHandler == null) {
1776 log.warn("Interface update aborted, defaultRoutingHandler is null");
1777 return;
1778 }
1779
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001780 Interface intf = intfs.stream().findFirst().get();
1781 Interface prevIntf = prevIntfs.stream().findFirst().get();
1782
1783 DeviceId deviceId = intf.connectPoint().deviceId();
1784 PortNumber portNum = intf.connectPoint().port();
1785
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001786 removeSubnetConfig(prevIntf.connectPoint(),
1787 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1788 new HashSet<>(intf.ipAddressesList())));
1789
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001790 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1791 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1792 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1793 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1794 // Update filtering objective and L2IG group bucket
1795 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1796 } else {
1797 // RemoveVlanNative
1798 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1799 }
1800 }
1801
1802 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1803 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1804 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1805 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1806 // Update filtering objective and L2IG group bucket
1807 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1808 } else {
1809 // RemoveVlanUntagged
1810 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1811 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001812 }
1813
1814 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1815 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001816 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1817 .filter(i -> !intf.vlanUntagged().equals(i))
1818 .filter(i -> !intf.vlanNative().equals(i))
1819 .forEach(vlanId -> updateVlanConfigInternal(
1820 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001821 }
1822
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001823 if (!intf.vlanNative().equals(VlanId.NONE)
1824 && !prevIntf.vlanNative().equals(intf.vlanNative())
1825 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1826 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1827 // Update filtering objective and L2IG group bucket
1828 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1829 } else {
1830 // AddVlanNative
1831 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1832 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001833 }
1834
1835 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1836 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001837 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1838 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1839 .filter(i -> !prevIntf.vlanNative().equals(i))
1840 .forEach(vlanId -> updateVlanConfigInternal(
1841 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001842 );
1843 }
1844
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001845 if (!intf.vlanUntagged().equals(VlanId.NONE)
1846 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1847 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1848 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1849 // Update filtering objective and L2IG group bucket
1850 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1851 } else {
1852 // AddVlanUntagged
1853 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1854 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001855 }
1856 addSubnetConfig(prevIntf.connectPoint(),
1857 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1858 new HashSet<>(prevIntf.ipAddressesList())));
1859 } catch (ConfigException e) {
1860 log.error("Error in configuration");
1861 }
1862 }
1863
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001864 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1865 VlanId vlanId, boolean pushVlan) {
1866 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1867 if (grpHandler == null) {
1868 log.warn("Failed to retrieve group handler for device {}", deviceId);
1869 return;
1870 }
1871
1872 // Update filtering objective for a single port
1873 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1874 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1875
1876 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1877 // Update L2IG bucket of the port
1878 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1879 } else {
1880 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1881 }
1882 }
1883
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001884 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1885 VlanId vlanId, boolean pushVlan, boolean install) {
1886 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1887 if (grpHandler == null) {
1888 log.warn("Failed to retrieve group handler for device {}", deviceId);
1889 return;
1890 }
1891
1892 // Update filtering objective for a single port
1893 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1894
1895 // Update filtering objective for multicast ingress port
1896 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1897
1898 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1899
1900 if (nextId != -1 && !install) {
1901 // Update next objective for a single port as an output port
1902 // Remove a single port from L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001903 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001904 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan074fae62018-04-29 18:11:37 -07001905 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
1906 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001907 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1908 // only if there is no port configured on that VLAN ID
1909 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1910 // Remove broadcast forwarding rule for the VLAN
1911 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1912 // Remove L2FG for VLAN
1913 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1914 } else {
1915 // Remove L2IG of the port
1916 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1917 }
1918 } else if (install) {
1919 if (nextId != -1) {
1920 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001921 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001922 } else {
1923 // Create L2FG for VLAN
1924 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1925 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1926 }
Charles Chan074fae62018-04-29 18:11:37 -07001927 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
1928 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001929 } else {
1930 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1931 }
1932 }
1933
1934 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1935 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1936 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1937
1938 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1939 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1940 .filter(intf -> !intf.connectPoint().equals(cp))
1941 .flatMap(intf -> intf.ipAddressesList().stream())
1942 .collect(Collectors.toSet());
1943 // 1. Partial subnet population
1944 // Remove routing rules for removed subnet from previous configuration,
1945 // which does not also exist in other interfaces in the same device
1946 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1947 .map(InterfaceIpAddress::subnetAddress)
1948 .collect(Collectors.toSet());
1949
1950 defaultRoutingHandler.revokeSubnet(
1951 ipPrefixSet.stream()
1952 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1953 .collect(Collectors.toSet()));
1954
1955 // 2. Interface IP punts
1956 // Remove IP punts for old Intf address
1957 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1958 .map(InterfaceIpAddress::ipAddress)
1959 .collect(Collectors.toSet());
1960 ipAddressSet.stream()
1961 .map(InterfaceIpAddress::ipAddress)
1962 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1963 .forEach(interfaceIpAddress ->
1964 routingRulePopulator.revokeSingleIpPunts(
1965 cp.deviceId(), interfaceIpAddress));
1966
1967 // 3. Host unicast routing rule
1968 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07001969 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001970 }
1971
1972 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1973 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1974 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1975
1976 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1977 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1978 .filter(intf -> !intf.connectPoint().equals(cp))
1979 .flatMap(intf -> intf.ipAddressesList().stream())
1980 .collect(Collectors.toSet());
1981 // 1. Partial subnet population
1982 // Add routing rules for newly added subnet, which does not also exist in
1983 // other interfaces in the same device
1984 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1985 .map(InterfaceIpAddress::subnetAddress)
1986 .collect(Collectors.toSet());
1987
1988 defaultRoutingHandler.populateSubnet(
1989 Collections.singleton(cp),
1990 ipPrefixSet.stream()
1991 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1992 .collect(Collectors.toSet()));
1993
1994 // 2. Interface IP punts
1995 // Add IP punts for new Intf address
1996 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1997 .map(InterfaceIpAddress::ipAddress)
1998 .collect(Collectors.toSet());
1999 ipAddressSet.stream()
2000 .map(InterfaceIpAddress::ipAddress)
2001 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2002 .forEach(interfaceIpAddress ->
2003 routingRulePopulator.populateSingleIpPunts(
2004 cp.deviceId(), interfaceIpAddress));
2005
2006 // 3. Host unicast routing rule
2007 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002008 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002009 }
sangho80f11cb2015-04-01 13:05:26 -07002010}