blob: 1f035d76a094b01688462e828d1c0c004a41d853 [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-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 Hart8ca2bc02017-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 Chan9640c812017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sanghob35a6192015-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 Chan47933752017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sanghob35a6192015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan47933752017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Das80980c72016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Pier Luigieba73a02018-01-16 10:47:50 +010041import org.onosproject.cluster.ClusterService;
42import org.onosproject.cluster.LeadershipService;
sanghob35a6192015-04-01 13:05:26 -070043import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070046import org.onosproject.mastership.MastershipService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080047import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070048import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070050import org.onosproject.net.Host;
51import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070052import org.onosproject.net.Link;
53import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080054import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070055import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070056import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070058import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070059import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070060import org.onosproject.net.config.basics.InterfaceConfig;
61import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070062import org.onosproject.net.config.basics.SubjectFactories;
Saurav Das45f48152018-01-18 12:07:33 -080063import org.onosproject.net.device.DeviceAdminService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070064import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080067import org.onosproject.net.flow.TrafficSelector;
68import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070069import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080070import org.onosproject.net.host.HostEvent;
71import org.onosproject.net.host.HostListener;
Charles Chan47933752017-11-30 15:37:50 -080072import org.onosproject.net.host.HostLocationProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080073import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070074import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070075import org.onosproject.net.intf.Interface;
76import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080077import org.onosproject.net.link.LinkEvent;
78import org.onosproject.net.link.LinkListener;
79import org.onosproject.net.link.LinkService;
Charles Chand55e84d2016-03-30 17:54:24 -070080import org.onosproject.net.mcast.McastEvent;
81import org.onosproject.net.mcast.McastListener;
82import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
96import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -080097import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070098import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070099import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700101import org.onosproject.segmentrouting.grouphandler.DestinationSet;
102import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100103import org.onosproject.segmentrouting.mcast.McastHandler;
104import org.onosproject.segmentrouting.mcast.McastRole;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700105import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800106import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
109
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800112import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
114
Saurav Das7bcbe702017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigib29144d2018-01-15 18:06:43 +0100116import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700120import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700121import org.onosproject.store.service.EventuallyConsistentMap;
122import org.onosproject.store.service.EventuallyConsistentMapBuilder;
123import org.onosproject.store.service.StorageService;
124import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800125import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700126import org.slf4j.Logger;
127import org.slf4j.LoggerFactory;
128
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800129import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800130import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800131import java.util.HashSet;
132import java.util.List;
133import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800134import java.util.Optional;
135import java.util.Set;
136import java.util.concurrent.ConcurrentHashMap;
137import java.util.concurrent.ConcurrentLinkedQueue;
138import java.util.concurrent.Executors;
139import java.util.concurrent.ScheduledExecutorService;
140import java.util.concurrent.ScheduledFuture;
141import java.util.concurrent.TimeUnit;
142import java.util.concurrent.atomic.AtomicBoolean;
143import java.util.stream.Collectors;
sanghob35a6192015-04-01 13:05:26 -0700144
Charles Chan3e783d02016-02-26 22:19:52 -0800145import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800146import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700147import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800148import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
149import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800150import static org.onosproject.segmentrouting.pwaas.PwaasUtil.configurationValidity;
Charles Chan3e783d02016-02-26 22:19:52 -0800151
Charles Chane849c192016-01-11 18:28:54 -0800152/**
153 * Segment routing manager.
154 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700155@Service
156@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700157public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700158
Charles Chan2c15aca2016-11-09 20:51:44 -0800159 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700160 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700163 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800166 private NeighbourResolutionService neighbourResolutionService;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100169 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700170
171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700172 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700173
174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700175 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700176
177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan47933752017-11-30 15:37:50 -0800178 HostLocationProbingService probingService;
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100181 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700182
183 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800184 DeviceAdminService deviceAdminService;
185
186 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800187 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700188
189 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100190 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700191
Charles Chan5270ed02016-01-30 23:22:37 -0800192 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800193 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700194
195 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800196 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700197
198 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100199 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700200
201 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800202 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700203
204 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700205 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800206
207 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800208 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800209
Saurav Das80980c72016-03-23 11:22:49 -0700210 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800211 public InterfaceService interfaceService;
212
Pier Luigieba73a02018-01-16 10:47:50 +0100213 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
214 public ClusterService clusterService;
215
216 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
217 public LeadershipService leadershipService;
218
Charles Chan47933752017-11-30 15:37:50 -0800219 @Property(name = "activeProbing", boolValue = true,
220 label = "Enable active probing to discover dual-homed hosts.")
221 boolean activeProbing = true;
222
Charles Chan03a73e02016-10-24 14:52:01 -0700223 ArpHandler arpHandler = null;
224 IcmpHandler icmpHandler = null;
225 IpHandler ipHandler = null;
226 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700227 ApplicationId appId;
228 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700229
Charles Chan03a73e02016-10-24 14:52:01 -0700230 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700231 private TunnelHandler tunnelHandler = null;
232 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700233 private InternalPacketProcessor processor = null;
234 private InternalLinkListener linkListener = null;
235 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700236 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100237 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800238 McastHandler mcastHandler = null;
239 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800240 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800241 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800242 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800243 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100244 private TopologyHandler topologyHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700245 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800246 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700247 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
248 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700249 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100250 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sanghob35a6192015-04-01 13:05:26 -0700251
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700252 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700253 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700254
Saurav Das4ce45962015-11-24 23:21:05 -0800255 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700256 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800257 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700258 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Saurav Das45f48152018-01-18 12:07:33 -0800259 Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800260 new ConcurrentHashMap<>();
261 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700262 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700263 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800264 */
Charles Chan47933752017-11-30 15:37:50 -0800265 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700266 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800267 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700268 * Per device next objective ID store with (device id + vlanid) as key.
269 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800270 */
Charles Chan47933752017-11-30 15:37:50 -0800271 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800272 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800273 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700274 * Per device next objective ID store with (device id + port + treatment + meta) as key.
275 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800276 */
Charles Chan47933752017-11-30 15:37:50 -0800277 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800278 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800279
Saurav Das4ce45962015-11-24 23:21:05 -0800280 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
281 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700282
Saurav Das7bcbe702017-06-13 15:35:54 -0700283 private AtomicBoolean programmingScheduled = new AtomicBoolean();
284
Charles Chand55e84d2016-03-30 17:54:24 -0700285 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700286 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
287 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700288 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700289 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800290 public SegmentRoutingDeviceConfig createConfig() {
291 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700292 }
293 };
Pier Ventref34966c2016-11-07 16:21:04 -0800294
Charles Chand55e84d2016-03-30 17:54:24 -0700295 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700296 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
297 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700298 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800299 @Override
300 public SegmentRoutingAppConfig createConfig() {
301 return new SegmentRoutingAppConfig();
302 }
303 };
Pier Ventref34966c2016-11-07 16:21:04 -0800304
Charles Chanfc5c7802016-05-17 13:13:55 -0700305 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
306 new ConfigFactory<ApplicationId, XConnectConfig>(
307 SubjectFactories.APP_SUBJECT_FACTORY,
308 XConnectConfig.class, "xconnect") {
309 @Override
310 public XConnectConfig createConfig() {
311 return new XConnectConfig();
312 }
313 };
Pier Ventref34966c2016-11-07 16:21:04 -0800314
Charles Chand55e84d2016-03-30 17:54:24 -0700315 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700316 new ConfigFactory<ApplicationId, McastConfig>(
317 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700318 McastConfig.class, "multicast") {
319 @Override
320 public McastConfig createConfig() {
321 return new McastConfig();
322 }
323 };
324
Charles Chan65238242017-06-22 18:03:14 -0700325 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700326 private static int numOfEventsQueued = 0;
327 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700328 private static int numOfHandlerExecution = 0;
329 private static int numOfHandlerScheduled = 0;
330
Charles Chan116188d2016-02-18 14:22:42 -0800331 /**
332 * Segment Routing App ID.
333 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800334 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800335
Charles Chane849c192016-01-11 18:28:54 -0800336 /**
337 * The default VLAN ID assigned to the interfaces without subnet config.
338 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800339 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700340
sanghob35a6192015-04-01 13:05:26 -0700341 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800342 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800343 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700344
345 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700346 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700347 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700348 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700349 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700350 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700351 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700352 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700353 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700354
Charles Chan59cc16d2017-02-02 16:20:42 -0800355 log.debug("Creating EC map vlannextobjectivestore");
356 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
357 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
358 vlanNextObjStore = vlanNextObjMapBuilder
359 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700360 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700361 .withTimestampProvider((k, v) -> new WallClockTimestamp())
362 .build();
363
Saurav Das4ce45962015-11-24 23:21:05 -0800364 log.debug("Creating EC map subnetnextobjectivestore");
365 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
366 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
367 portNextObjStore = portNextObjMapBuilder
368 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700369 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800370 .withTimestampProvider((k, v) -> new WallClockTimestamp())
371 .build();
372
sangho0b2b6d12015-05-20 22:16:38 -0700373 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
374 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700375 tunnelStore = tunnelMapBuilder
376 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700377 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700378 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700379 .build();
380
381 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
382 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700383 policyStore = policyMapBuilder
384 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700385 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700386 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700387 .build();
388
Saurav Das80980c72016-03-23 11:22:49 -0700389 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800390 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700391 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800392 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800393 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
394 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700395 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800396 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700397 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800398 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800399 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
400 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800401 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
402 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700403 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700404 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700405 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
406 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800407 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
408 "staleLinkAge", "15000");
409 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
410 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800411 compCfgService.registerProperties(getClass());
412 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700413
Charles Chanb8e10c82015-10-14 11:24:40 -0700414 processor = new InternalPacketProcessor();
415 linkListener = new InternalLinkListener();
416 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700417 appCfgHandler = new AppConfigHandler(this);
418 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700419 mcastHandler = new McastHandler(this);
420 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800421 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700422 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800423 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800424 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100425 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700426
Charles Chan3e783d02016-02-26 22:19:52 -0800427 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700428 cfgService.registerConfigFactory(deviceConfigFactory);
429 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700430 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700431 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800432 log.info("Configuring network before adding listeners");
Charles Chan132393a2018-01-04 14:26:07 -0800433 cfgListener.configureNetwork();
434
Charles Chan5270ed02016-01-30 23:22:37 -0800435 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700436 packetService.addProcessor(processor, PacketProcessor.director(2));
437 linkService.addListener(linkListener);
438 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700439 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700440 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100441 topologyService.addListener(topologyListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700442
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800443 l2TunnelHandler.init();
444
sanghob35a6192015-04-01 13:05:26 -0700445 log.info("Started");
446 }
447
Saurav Das45f48152018-01-18 12:07:33 -0800448 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700449 return new KryoNamespace.Builder()
450 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700451 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800452 VlanNextObjectiveStoreKey.class,
453 DestinationSet.class,
454 NextNeighbors.class,
455 Tunnel.class,
456 DefaultTunnel.class,
457 Policy.class,
458 TunnelPolicy.class,
459 Policy.Type.class,
460 PortNextObjectiveStoreKey.class,
461 XConnectStoreKey.class,
462 L2Tunnel.class,
463 L2TunnelPolicy.class,
464 DefaultL2Tunnel.class,
465 DefaultL2TunnelPolicy.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700466 );
467 }
468
sanghob35a6192015-04-01 13:05:26 -0700469 @Deactivate
470 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700471 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700472 cfgService.unregisterConfigFactory(deviceConfigFactory);
473 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700474 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700475 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800476 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700477
Charles Chanc7a8a682017-06-19 00:43:31 -0700478 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700479 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700480 linkService.removeListener(linkListener);
481 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700482 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700483 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100484 topologyService.removeListener(topologyListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700485
Charles Chan0aa674e2017-02-23 15:44:08 -0800486 neighbourResolutionService.unregisterNeighbourHandlers(appId);
487
sanghob35a6192015-04-01 13:05:26 -0700488 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700489 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700490 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700491 groupHandlerMap.clear();
492
Saurav Das7bcbe702017-06-13 15:35:54 -0700493 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800494 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700495 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700496 tunnelStore.destroy();
497 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100498
499 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700500 log.info("Stopped");
501 }
502
Charles Chan47933752017-11-30 15:37:50 -0800503 @Modified
504 private void modified(ComponentContext context) {
505 Dictionary<?, ?> properties = context.getProperties();
506 if (properties == null) {
507 return;
508 }
509
510 String strActiveProving = Tools.get(properties, "activeProbing");
511 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
512
513 if (expectActiveProbing != activeProbing) {
514 activeProbing = expectActiveProbing;
515 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
516 }
517 }
518
sangho1e575652015-05-14 00:39:53 -0700519 @Override
520 public List<Tunnel> getTunnels() {
521 return tunnelHandler.getTunnels();
522 }
523
524 @Override
sangho71abe1b2015-06-29 14:58:47 -0700525 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
526 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700527 }
528
529 @Override
sangho71abe1b2015-06-29 14:58:47 -0700530 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700531 for (Policy policy: policyHandler.getPolicies()) {
532 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
533 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
534 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
535 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700536 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700537 }
538 }
539 }
sangho71abe1b2015-06-29 14:58:47 -0700540 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700541 }
542
543 @Override
sangho71abe1b2015-06-29 14:58:47 -0700544 public PolicyHandler.Result removePolicy(Policy policy) {
545 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700546 }
547
548 @Override
sangho71abe1b2015-06-29 14:58:47 -0700549 public PolicyHandler.Result createPolicy(Policy policy) {
550 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700551 }
552
553 @Override
554 public List<Policy> getPolicies() {
555 return policyHandler.getPolicies();
556 }
557
Saurav Das59232cf2016-04-27 18:35:50 -0700558 @Override
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700559 public Set<L2TunnelDescription> getL2TunnelDescriptions() {
560 return l2TunnelHandler.getL2Descriptions();
561 }
562
563 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800564 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700565 return l2TunnelHandler.getL2Tunnels();
566 }
567
568 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800569 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700570 return l2TunnelHandler.getL2Policies();
571 }
572
573 @Override
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700574 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
575
576 Set<L2TunnelDescription> pseudowires = l2TunnelHandler.getL2Descriptions();
577
578 pseudowires.addAll(bulkPseudowires);
579 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
580
581 // check global validity for all the new pseudowires, if it fails
582 // do not add any of them
583 boolean res = configurationValidity(pseudowires);
584 if (res) {
585 l2TunnelHandler.deploy(newPseudowires);
586 return L2TunnelHandler.Result.SUCCESS;
587 } else {
588 log.error("Bulk pseudowires {} can not be added, error in global configuration!",
589 newPseudowires);
590 return L2TunnelHandler.Result.ADDITION_ERROR;
591 }
592 }
593
594 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800595 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
596
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700597 Set<L2TunnelDescription> newPseudowires = l2TunnelHandler.getL2Descriptions();
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800598
599 // corner case where we try to add the exact same pseudowire
600 if (newPseudowires.contains(l2TunnelDescription)) {
601 log.info("Pseudowire with {} already exists!", l2TunnelDescription);
602 return L2TunnelHandler.Result.SUCCESS;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700603 }
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800604 // add the new pseudowire to the Set
605 newPseudowires.add(l2TunnelDescription);
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800606 // validate the new set of pseudowires
607 boolean res = configurationValidity(newPseudowires);
608 if (res) {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800609 // deploy a set with ONLY the new pseudowire
610 newPseudowires = new HashSet<>();
611 newPseudowires.add(l2TunnelDescription);
612 l2TunnelHandler.deploy(newPseudowires);
613
614 log.info("Pseudowire with {} deployment started, check log for any errors in this process!",
615 l2TunnelDescription.l2Tunnel().tunnelId());
616 return L2TunnelHandler.Result.SUCCESS;
617 } else {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800618 log.error("Pseudowire with {} can not be added!", l2TunnelDescription.l2Tunnel().tunnelId());
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700619 return L2TunnelHandler.Result.ADDITION_ERROR;
620 }
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700621 }
622
623 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800624 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700625
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800626 List<L2Tunnel> tunnels = getL2Tunnels();
627 List<L2TunnelPolicy> policies = getL2Policies();
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700628
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800629 // get the pseudowire, if it exists
630 List<L2TunnelDescription> pseudowires = tunnels.stream().map(l2Tunnel -> {
631 L2TunnelPolicy policy = null;
632 for (L2TunnelPolicy l2Policy : policies) {
633 if (l2Policy.tunnelId() == l2Tunnel.tunnelId()) {
634 policy = l2Policy;
635 break;
636 }
637 }
638
639 return new DefaultL2TunnelDescription(l2Tunnel, policy);
640 }).filter(l2desc ->
641 l2desc.l2Tunnel().tunnelId() == pwId
642 ).collect(Collectors.toList());
643
644 if (pseudowires.size() == 0) {
645 log.error("Pseudowire with id {} does not exist", pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700646 return L2TunnelHandler.Result.REMOVAL_ERROR;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800647 } else {
648
649 l2TunnelHandler.tearDown(new HashSet<>(pseudowires));
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800650 log.info("Removal of pseudowire with {} started, check log for any errors in this process!",
651 pwId);
652 return L2TunnelHandler.Result.SUCCESS;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700653 }
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700654 }
655
656 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700657 public void rerouteNetwork() {
658 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700659 }
660
Charles Chanc81c45b2016-10-20 17:02:44 -0700661 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800662 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
663 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800664 deviceConfiguration.getRouters().forEach(device ->
665 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700666 return deviceSubnetMap;
667 }
668
Saurav Dasc88d4662017-05-15 15:34:25 -0700669
670 @Override
671 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
672 if (defaultRoutingHandler != null) {
673 return defaultRoutingHandler.getCurrentEmcpSpgMap();
674 } else {
675 return null;
676 }
677 }
678
679 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700680 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
681 if (dsNextObjStore != null) {
682 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700683 } else {
684 return ImmutableMap.of();
685 }
686 }
687
Saurav Dasceccf242017-08-03 18:30:35 -0700688 @Override
689 public void verifyGroups(DeviceId id) {
690 DefaultGroupHandler gh = groupHandlerMap.get(id);
691 if (gh != null) {
692 gh.triggerBucketCorrector();
693 }
694 }
695
Saurav Dasc568c342018-01-25 09:49:01 -0800696 @Override
697 public ImmutableMap<Link, Boolean> getSeenLinks() {
698 return linkHandler.getSeenLinks();
699 }
700
701 @Override
702 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
703 return linkHandler.getDownedPorts();
704 }
705
Pier Luigib29144d2018-01-15 18:06:43 +0100706 @Override
707 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
708 return mcastHandler.getMcastNextIds(mcastIp);
709 }
710
711 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100712 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100713 return mcastHandler.getMcastRoles(mcastIp);
714 }
715
716 @Override
717 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
718 return mcastHandler.getMcastPaths(mcastIp);
719 }
720
sanghof9d0bf12015-05-19 11:57:42 -0700721 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700722 * Extracts the application ID from the manager.
723 *
724 * @return application ID
725 */
726 public ApplicationId appId() {
727 return appId;
728 }
729
730 /**
731 * Returns the device configuration.
732 *
733 * @return device configuration
734 */
735 public DeviceConfiguration deviceConfiguration() {
736 return deviceConfiguration;
737 }
738
739 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700740 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700741 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700742 *
743 * @return next objective ID store
744 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700745 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
746 dsNextObjStore() {
747 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700748 }
749
750 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700751 * Per device next objective ID store with (device id + vlanid) as key.
752 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700753 *
754 * @return vlan next object store
755 */
756 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
757 return vlanNextObjStore;
758 }
759
760 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700761 * Per device next objective ID store with (device id + port + treatment + meta) as key.
762 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700763 *
764 * @return port next object store.
765 */
766 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
767 return portNextObjStore;
768 }
769
770 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700771 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
772 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700773 *
774 * @return MPLS-ECMP value
775 */
776 public boolean getMplsEcmp() {
777 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
778 .getConfig(this.appId, SegmentRoutingAppConfig.class);
779 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
780 }
781
782 /**
sanghof9d0bf12015-05-19 11:57:42 -0700783 * Returns the tunnel object with the tunnel ID.
784 *
785 * @param tunnelId Tunnel ID
786 * @return Tunnel reference
787 */
sangho1e575652015-05-14 00:39:53 -0700788 public Tunnel getTunnel(String tunnelId) {
789 return tunnelHandler.getTunnel(tunnelId);
790 }
791
Charles Chan7ffd81f2017-02-08 15:52:08 -0800792 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700793 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800794 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800795 * <p>
796 * Only returns the first match if there are multiple untagged VLAN configured
797 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700798 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800799 * @param connectPoint connect point
800 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700801 */
Charles Chan65238242017-06-22 18:03:14 -0700802 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800803 return interfaceService.getInterfacesByPort(connectPoint).stream()
804 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
805 .map(Interface::vlanUntagged)
806 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700807 }
808
sangho1e575652015-05-14 00:39:53 -0700809 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800810 * Returns tagged VLAN configured on given connect point.
811 * <p>
812 * Returns all matches if there are multiple tagged VLAN configured
813 * on the connect point.
814 *
815 * @param connectPoint connect point
816 * @return tagged VLAN or empty set if not configured
817 */
Charles Chan65238242017-06-22 18:03:14 -0700818 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800819 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
820 return interfaces.stream()
821 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700822 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800823 .collect(Collectors.toSet());
824 }
825
826 /**
827 * Returns native VLAN configured on given connect point.
828 * <p>
829 * Only returns the first match if there are multiple native VLAN configured
830 * on the connect point.
831 *
832 * @param connectPoint connect point
833 * @return native VLAN or null if not configured
834 */
Charles Chan65238242017-06-22 18:03:14 -0700835 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800836 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
837 return interfaces.stream()
838 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
839 .map(Interface::vlanNative)
840 .findFirst()
841 .orElse(null);
842 }
843
844 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700845 * Returns internal VLAN for untagged hosts on given connect point.
846 * <p>
847 * The internal VLAN is either vlan-untagged for an access port,
848 * or vlan-native for a trunk port.
849 *
850 * @param connectPoint connect point
851 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
852 */
Pier Luigi96fe0772018-02-28 12:10:50 +0100853 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700854 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
855 VlanId nativeVlanId = getNativeVlanId(connectPoint);
856 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
857 }
858
859 /**
Charles Chan65238242017-06-22 18:03:14 -0700860 * Returns optional pair device ID of given device.
861 *
862 * @param deviceId device ID
863 * @return optional pair device ID. Might be empty if pair device is not configured
864 */
865 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
866 SegmentRoutingDeviceConfig deviceConfig =
867 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
868 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
869 }
870 /**
871 * Returns optional pair device local port of given device.
872 *
873 * @param deviceId device ID
874 * @return optional pair device ID. Might be empty if pair device is not configured
875 */
876 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
877 SegmentRoutingDeviceConfig deviceConfig =
878 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
879 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
880 }
881
882 /**
Charles Chan2fde6d42017-08-23 14:46:43 -0700883 * Determine if current instance is the master of given connect point.
884 *
885 * @param cp connect point
886 * @return true if current instance is the master of given connect point
887 */
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700888 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan2fde6d42017-08-23 14:46:43 -0700889 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
890 if (!isMaster) {
891 log.debug(NOT_MASTER, cp);
892 }
893 return isMaster;
894 }
895
896 /**
Charles Chan9640c812017-08-23 13:55:39 -0700897 * Returns locations of given resolved route.
898 *
899 * @param resolvedRoute resolved route
900 * @return locations of nexthop. Might be empty if next hop is not found
901 */
902 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
903 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
904 return Optional.ofNullable(hostService.getHost(hostId))
905 .map(Host::locations).orElse(Sets.newHashSet())
906 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
907 }
908
909 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800910 * Returns vlan port map of given device.
911 *
912 * @param deviceId device id
913 * @return vlan-port multimap
914 */
915 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
916 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
917
918 interfaceService.getInterfaces().stream()
919 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
920 .forEach(intf -> {
921 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700922 intf.vlanTagged().forEach(vlanTagged ->
923 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
924 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800925 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
926 });
927 vlanPortMap.removeAll(VlanId.NONE);
928
929 return vlanPortMap;
930 }
931
932 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800933 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800934 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700935 *
936 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800937 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800938 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700939 */
Charles Chan65238242017-06-22 18:03:14 -0700940 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700941 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800942 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
943 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700944 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800945 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800946 + "device {} not found", deviceId);
947 return -1;
948 }
949 }
950
951 /**
952 * Returns the next objective ID for the given portNumber, given the treatment.
953 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700954 * would result in different objectives. If the next object does not exist,
955 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800956 *
957 * @param deviceId Device ID
958 * @param portNum port number on device for which NextObjective is queried
959 * @param treatment the actions to apply on the packets (should include outport)
960 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700961 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700962 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800963 */
964 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
965 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700966 TrafficSelector meta,
967 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800968 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
969 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700970 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800971 } else {
Charles Chane849c192016-01-11 18:28:54 -0800972 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
973 + " not found", deviceId);
974 return -1;
975 }
976 }
977
Saurav Dasc88d4662017-05-15 15:34:25 -0700978 /**
979 * Returns the group handler object for the specified device id.
980 *
981 * @param devId the device identifier
982 * @return the groupHandler object for the device id, or null if not found
983 */
Charles Chan65238242017-06-22 18:03:14 -0700984 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700985 return groupHandlerMap.get(devId);
986 }
987
988 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700989 * Returns the default routing handler object.
990 *
991 * @return the default routing handler object
992 */
993 public DefaultRoutingHandler getRoutingHandler() {
994 return defaultRoutingHandler;
995 }
996
sanghob35a6192015-04-01 13:05:26 -0700997 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700998 @Override
999 public void process(PacketContext context) {
1000
1001 if (context.isHandled()) {
1002 return;
1003 }
1004
1005 InboundPacket pkt = context.inPacket();
1006 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001007
1008 if (ethernet == null) {
1009 return;
1010 }
1011
Saurav Das7bcbe702017-06-13 15:35:54 -07001012 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1013 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001014 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001015 log.warn("Received unexpected ARP packet on {}",
1016 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001017 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001018 return;
sanghob35a6192015-04-01 13:05:26 -07001019 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001020 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1021 //ipHandler.addToPacketBuffer(ipv4Packet);
1022 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1023 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001024 } else {
Charles Chan50035632017-01-13 17:20:44 -08001025 // NOTE: We don't support IP learning at this moment so this
1026 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001027 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001028 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001029 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1030 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001031 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001032 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001033 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1034 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1035 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1036 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1037 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1038 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001039 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001040 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001041 }
1042 } else {
1043 // NOTE: We don't support IP learning at this moment so this
1044 // is not necessary. Also it causes duplication of DHCPv6 packets.
1045 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1046 }
sanghob35a6192015-04-01 13:05:26 -07001047 }
1048 }
1049 }
1050
1051 private class InternalLinkListener implements LinkListener {
1052 @Override
1053 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001054 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1055 event.type() == LinkEvent.Type.LINK_UPDATED ||
1056 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001057 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001058 scheduleEventHandlerIfNotScheduled(event);
1059 }
1060 }
1061 }
1062
1063 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001064 @Override
1065 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001066 switch (event.type()) {
1067 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001068 case PORT_UPDATED:
1069 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001070 case DEVICE_UPDATED:
1071 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001072 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001073 scheduleEventHandlerIfNotScheduled(event);
1074 break;
1075 default:
1076 }
1077 }
1078 }
1079
Pier Luigi83f919b2018-02-15 16:33:08 +01001080 /**
1081 * Internal listener for topology events.
1082 */
1083 private class InternalTopologyListener implements TopologyListener {
1084 @Override
1085 public void event(TopologyEvent event) {
1086 switch (event.type()) {
1087 case TOPOLOGY_CHANGED:
1088 log.debug("Event {} received from TopologyService", event.type());
1089 scheduleEventHandlerIfNotScheduled(event);
1090 break;
1091 default:
1092 }
1093 }
1094 }
1095
Saurav Das4ce45962015-11-24 23:21:05 -08001096 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001097 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001098 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001099 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001100 numOfEventsQueued++;
1101
1102 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1103 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001104 eventHandlerFuture = executorService
1105 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1106 numOfHandlerScheduled++;
1107 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001108 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001109 numOfEventsQueued,
1110 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001111 }
sanghob35a6192015-04-01 13:05:26 -07001112 }
1113
1114 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001115 @Override
sanghob35a6192015-04-01 13:05:26 -07001116 public void run() {
Pier Luigieefa2762018-02-12 09:56:20 +01001117 while (true) {
1118 try {
Saurav Das4ce45962015-11-24 23:21:05 -08001119 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001120 Event event;
1121 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001122 if (!eventQueue.isEmpty()) {
1123 event = eventQueue.poll();
1124 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001125 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001126 numOfHandlerExecution++;
1127 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1128 numOfHandlerExecution, numOfEventsExecuted);
1129 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001130 }
sangho20eff1d2015-04-13 15:15:58 -07001131 }
Pier Luigi83f919b2018-02-15 16:33:08 +01001132 // TODO We should also change SR routing and PW to listen to TopologyEvents
Charles Chanb1f8c762017-03-29 16:39:05 -07001133 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1134 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Das45f48152018-01-18 12:07:33 -08001135 linkHandler.processLinkAdded((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001136 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Saurav Das45f48152018-01-18 12:07:33 -08001137 linkHandler.processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001138 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1139 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1140 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001141 DeviceId deviceId = ((Device) event.subject()).id();
1142 if (deviceService.isAvailable(deviceId)) {
Saurav Dase0d4c872018-03-05 14:37:16 -08001143 log.info("** DEVICE UP Processing device event {} "
1144 + "for available device {}",
Saurav Das837e0bb2015-10-30 17:45:38 -07001145 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001146 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001147 } else {
Saurav Dase0d4c872018-03-05 14:37:16 -08001148 log.info(" ** DEVICE DOWN Processing device event {}"
1149 + " for unavailable device {}",
Pier Luigieefa2762018-02-12 09:56:20 +01001150 event.type(), ((Device) event.subject()).id());
Saurav Das80980c72016-03-23 11:22:49 -07001151 processDeviceRemoved((Device) event.subject());
1152 }
Saurav Das1a129a02016-11-18 15:21:57 -08001153 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001154 // typically these calls come when device is added first time
1155 // so port filtering rules are handled at the device_added event.
1156 // port added calls represent all ports on the device,
1157 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001158 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001159 ((DeviceEvent) event).subject().id(),
1160 ((DeviceEvent) event).port().number(),
1161 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001162 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001163 // these calls happen for every subsequent event
1164 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001165 log.info("** PORT UPDATED {}/{} -> {}",
1166 event.subject(),
1167 ((DeviceEvent) event).port(),
1168 event.type());
1169 processPortUpdated(((Device) event.subject()),
1170 ((DeviceEvent) event).port());
Pier Luigi83f919b2018-02-15 16:33:08 +01001171 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1172 // Process topology event, needed for all modules relying on
1173 // topology service for path computation
1174 TopologyEvent topologyEvent = (TopologyEvent) event;
1175 log.info("Processing topology event {}, topology age {}, reasons {}",
1176 event.type(), topologyEvent.subject().time(),
1177 topologyEvent.reasons().size());
1178 topologyHandler.processTopologyChange(topologyEvent.reasons());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001179 } else {
1180 log.warn("Unhandled event type: {}", event.type());
1181 }
Pier Luigieefa2762018-02-12 09:56:20 +01001182 } catch (Exception e) {
1183 log.error("SegmentRouting event handler thread thrown an exception: {}",
1184 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001185 }
1186 }
sanghob35a6192015-04-01 13:05:26 -07001187 }
1188 }
1189
Saurav Das45f48152018-01-18 12:07:33 -08001190 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001191 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001192
1193 // NOTE: Punt ARP/NDP even when the device is not configured.
1194 // Host learning without network config is required for CORD config generator.
1195 routingRulePopulator.populateIpPunts(device.id());
1196 routingRulePopulator.populateArpNdpPunts(device.id());
1197
Charles Chan0b4e6182015-11-03 10:42:14 -08001198 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001199 log.warn("Device configuration unavailable. Device {} will be "
1200 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001201 return;
1202 }
Charles Chan2199c302016-04-23 17:36:10 -07001203 processDeviceAddedInternal(device.id());
1204 }
1205
1206 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001207 // Irrespective of whether the local is a MASTER or not for this device,
1208 // we need to create a SR-group-handler instance. This is because in a
1209 // multi-instance setup, any instance can initiate forwarding/next-objectives
1210 // for any switch (even if this instance is a SLAVE or not even connected
1211 // to the switch). To handle this, a default-group-handler instance is necessary
1212 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001213 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1214 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001215 DefaultGroupHandler groupHandler;
1216 try {
1217 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001218 createGroupHandler(deviceId,
1219 appId,
1220 deviceConfiguration,
1221 linkService,
1222 flowObjectiveService,
1223 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001224 } catch (DeviceConfigNotFoundException e) {
1225 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1226 return;
1227 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001228 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001229 deviceId);
1230 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001231 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001232
Charles Chan2199c302016-04-23 17:36:10 -07001233 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001234 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001235 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001236 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001237 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001238 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001239 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001240 }
Charles Chan5270ed02016-01-30 23:22:37 -08001241
Charles Chan03a73e02016-10-24 14:52:01 -07001242 appCfgHandler.init(deviceId);
1243 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001244 }
1245
Saurav Das80980c72016-03-23 11:22:49 -07001246 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001247 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001248 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001249 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001250 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001251 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001252 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001253 portNextObjStore.entrySet().stream()
1254 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001255 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001256 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001257
Saurav Dasceccf242017-08-03 18:30:35 -07001258 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1259 if (gh != null) {
1260 gh.shutdown();
1261 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001262 // Note that a switch going down is associated with all of its links
1263 // going down as well, but it is treated as a single switch down event
1264 // while the link-downs are ignored.
1265 defaultRoutingHandler
1266 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Saurav Dasc568c342018-01-25 09:49:01 -08001267 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001268 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001269
1270 // Cleanup all internal groupHandler stores for this device. Should be
1271 // done after all rerouting or rehashing has been completed
1272 groupHandlerMap.entrySet()
1273 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001274 }
1275
Saurav Das1a129a02016-11-18 15:21:57 -08001276 private void processPortUpdated(Device device, Port port) {
1277 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1278 log.warn("Device configuration uploading. Not handling port event for"
1279 + "dev: {} port: {}", device.id(), port.number());
1280 return;
1281 }
Saurav Das018605f2017-02-18 14:05:44 -08001282
1283 if (!mastershipService.isLocalMaster(device.id())) {
1284 log.debug("Not master for dev:{} .. not handling port updated event"
1285 + "for port {}", device.id(), port.number());
1286 return;
1287 }
1288
1289 // first we handle filtering rules associated with the port
1290 if (port.isEnabled()) {
1291 log.info("Switchport {}/{} enabled..programming filters",
1292 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001293 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001294 } else {
1295 log.info("Switchport {}/{} disabled..removing filters",
1296 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001297 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001298 }
Saurav Das1a129a02016-11-18 15:21:57 -08001299
1300 // portUpdated calls are for ports that have gone down or up. For switch
1301 // to switch ports, link-events should take care of any re-routing or
1302 // group editing necessary for port up/down. Here we only process edge ports
1303 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001304 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1305 VlanId untaggedVlan = getUntaggedVlanId(cp);
1306 VlanId nativeVlan = getNativeVlanId(cp);
1307 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001308
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001309 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001310 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001311 + "dev/port: {}/{}", device.id(), port.number());
1312 return;
1313 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001314 if (untaggedVlan != null) {
1315 processEdgePort(device, port, untaggedVlan, true);
1316 }
1317 if (nativeVlan != null) {
1318 processEdgePort(device, port, nativeVlan, true);
1319 }
1320 if (!taggedVlans.isEmpty()) {
1321 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1322 }
Saurav Das1a129a02016-11-18 15:21:57 -08001323 }
1324
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001325 private void processEdgePort(Device device, Port port, VlanId vlanId,
1326 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001327 boolean portUp = port.isEnabled();
1328 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001329 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001330 port.number(), vlanId);
Charles Chan47933752017-11-30 15:37:50 -08001331 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001332 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001333 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001334 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001335 }
1336
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001337 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001338 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001339 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001340 } else {
1341 log.warn("Group handler not found for dev:{}. Not handling edge port"
1342 + " {} event for port:{}", device.id(),
1343 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001344 }
1345 }
sangho1e575652015-05-14 00:39:53 -07001346
Charles Chan27fe1a52017-10-20 16:06:55 -07001347 private void createOrUpdateDeviceConfiguration() {
1348 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001349 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001350 deviceConfiguration = new DeviceConfiguration(this);
1351 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001352 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001353 deviceConfiguration.updateConfig();
1354 }
1355 }
1356
Pier Ventre10bd8d12016-11-26 21:05:22 -08001357 /**
1358 * Registers the given connect point with the NRS, this is necessary
1359 * to receive the NDP and ARP packets from the NRS.
1360 *
1361 * @param portToRegister connect point to register
1362 */
1363 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001364 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001365 portToRegister,
1366 neighbourHandler,
1367 appId
1368 );
1369 }
1370
Charles Chand6832882015-10-05 17:50:33 -07001371 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001372 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001373 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001374
Charles Chane849c192016-01-11 18:28:54 -08001375 /**
1376 * Constructs the internal network config listener.
1377 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001378 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001379 */
Charles Chan65238242017-06-22 18:03:14 -07001380 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001381 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001382 }
1383
Charles Chane849c192016-01-11 18:28:54 -08001384 /**
1385 * Reads network config and initializes related data structure accordingly.
1386 */
Charles Chan47933752017-11-30 15:37:50 -08001387 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001388 log.info("Configuring network ...");
Charles Chan27fe1a52017-10-20 16:06:55 -07001389 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001390
Charles Chan2c15aca2016-11-09 20:51:44 -08001391 arpHandler = new ArpHandler(srManager);
1392 icmpHandler = new IcmpHandler(srManager);
1393 ipHandler = new IpHandler(srManager);
1394 routingRulePopulator = new RoutingRulePopulator(srManager);
1395 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001396
1397 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1398 groupHandlerMap, tunnelStore);
1399 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1400 flowObjectiveService,
1401 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001402 // add a small delay to absorb multiple network config added notifications
1403 if (!programmingScheduled.get()) {
Saurav Dase7f51012018-02-09 17:26:45 -08001404 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das7bcbe702017-06-13 15:35:54 -07001405 programmingScheduled.set(true);
1406 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1407 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001408 }
Charles Chan2199c302016-04-23 17:36:10 -07001409 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001410 }
1411
Charles Chand6832882015-10-05 17:50:33 -07001412 @Override
1413 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001414 // TODO move this part to NetworkConfigEventHandler
1415 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1416 switch (event.type()) {
1417 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001418 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001419 configureNetwork();
1420 break;
1421 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001422 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001423 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001424 // TODO support dynamic configuration
1425 break;
1426 default:
1427 break;
1428 }
1429 } else if (event.configClass().equals(InterfaceConfig.class)) {
1430 switch (event.type()) {
1431 case CONFIG_ADDED:
1432 log.info("Interface Config added for {}", event.subject());
1433 configureNetwork();
1434 break;
1435 case CONFIG_UPDATED:
1436 log.info("Interface Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001437 createOrUpdateDeviceConfiguration();
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001438
1439 // Following code will be uncommented when [CORD-634] is fully implemented.
1440 // [CORD-634] Add dynamic config support for interfaces
1441 updateInterface((InterfaceConfig) event.config().get(),
1442 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001443 // TODO support dynamic configuration
1444 break;
1445 default:
1446 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001447 }
Charles Chan5270ed02016-01-30 23:22:37 -08001448 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001449 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001450 switch (event.type()) {
1451 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001452 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001453 break;
1454 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001455 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001456 break;
1457 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001458 appCfgHandler.processAppConfigRemoved(event);
1459 break;
1460 default:
1461 break;
1462 }
Saurav Dase7f51012018-02-09 17:26:45 -08001463 log.info("App config event .. configuring network");
Charles Chan03a73e02016-10-24 14:52:01 -07001464 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001465 } else if (event.configClass().equals(XConnectConfig.class)) {
1466 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1467 switch (event.type()) {
1468 case CONFIG_ADDED:
1469 xConnectHandler.processXConnectConfigAdded(event);
1470 break;
1471 case CONFIG_UPDATED:
1472 xConnectHandler.processXConnectConfigUpdated(event);
1473 break;
1474 case CONFIG_REMOVED:
1475 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001476 break;
1477 default:
1478 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001479 }
Charles Chand6832882015-10-05 17:50:33 -07001480 }
1481 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001482
Charles Chan50443e82018-01-03 16:26:32 -08001483 @Override
1484 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001485 if (event.type() == CONFIG_REGISTERED ||
1486 event.type() == CONFIG_UNREGISTERED) {
1487 log.debug("Ignore event {} due to type mismatch", event);
1488 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001489 }
Saurav Dase7f51012018-02-09 17:26:45 -08001490
1491 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1492 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1493 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001494 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001495 log.debug("Ignore event {} due to class mismatch", event);
1496 return false;
1497 }
1498
1499 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001500 }
1501
Saurav Das7bcbe702017-06-13 15:35:54 -07001502 private final class ConfigChange implements Runnable {
1503 @Override
1504 public void run() {
1505 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001506 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001507 for (Device device : deviceService.getDevices()) {
1508 processDeviceAdded(device);
1509 }
1510 defaultRoutingHandler.startPopulationProcess();
1511 }
1512 }
Charles Chand6832882015-10-05 17:50:33 -07001513 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001514
1515 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001516 @Override
1517 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001518 switch (event.type()) {
1519 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001520 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001521 break;
1522 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001523 hostHandler.processHostMovedEvent(event);
Charles Chan2fde6d42017-08-23 14:46:43 -07001524 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001525 break;
1526 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001527 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001528 break;
1529 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001530 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001531 break;
1532 default:
1533 log.warn("Unsupported host event type: {}", event.type());
1534 break;
1535 }
1536 }
1537 }
1538
Charles Chand55e84d2016-03-30 17:54:24 -07001539 private class InternalMcastListener implements McastListener {
1540 @Override
1541 public void event(McastEvent event) {
1542 switch (event.type()) {
1543 case SOURCE_ADDED:
Pier Luigi57d41792018-02-26 12:31:38 +01001544 case SOURCE_UPDATED:
Charles Chand55e84d2016-03-30 17:54:24 -07001545 case SINK_ADDED:
Charles Chand55e84d2016-03-30 17:54:24 -07001546 case SINK_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001547 case ROUTE_REMOVED:
Pier Luigi05514fd2018-02-28 17:24:03 +01001548 mcastHandler.processMcastEvent(event);
Pier Luigi9930da52018-02-02 16:19:11 +01001549 break;
1550 case ROUTE_ADDED:
Charles Chand55e84d2016-03-30 17:54:24 -07001551 default:
1552 break;
1553 }
1554 }
1555 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001556
Charles Chan03a73e02016-10-24 14:52:01 -07001557 private class InternalRouteEventListener implements RouteListener {
1558 @Override
1559 public void event(RouteEvent event) {
1560 switch (event.type()) {
1561 case ROUTE_ADDED:
1562 routeHandler.processRouteAdded(event);
1563 break;
1564 case ROUTE_UPDATED:
1565 routeHandler.processRouteUpdated(event);
1566 break;
1567 case ROUTE_REMOVED:
1568 routeHandler.processRouteRemoved(event);
1569 break;
Charles Chan2fde6d42017-08-23 14:46:43 -07001570 case ALTERNATIVE_ROUTES_CHANGED:
1571 routeHandler.processAlternativeRoutesChanged(event);
1572 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001573 default:
1574 break;
1575 }
1576 }
1577 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001578
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001579 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1580 try {
1581 Set<Interface> intfs = conf.getInterfaces();
1582 Set<Interface> prevIntfs = prevConf.getInterfaces();
1583
1584 // Now we only handle one interface config at each port.
1585 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1586 log.warn("Interface update aborted - one at a time is allowed, " +
1587 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1588 return;
1589 }
1590
1591 Interface intf = intfs.stream().findFirst().get();
1592 Interface prevIntf = prevIntfs.stream().findFirst().get();
1593
1594 DeviceId deviceId = intf.connectPoint().deviceId();
1595 PortNumber portNum = intf.connectPoint().port();
1596
1597 if (!mastershipService.isLocalMaster(deviceId)) {
1598 log.debug("CONFIG_UPDATED event for interfaces should be " +
1599 "handled by master node for device {}", deviceId);
1600 return;
1601 }
1602
1603 removeSubnetConfig(prevIntf.connectPoint(),
1604 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1605 new HashSet<>(intf.ipAddressesList())));
1606
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001607 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1608 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1609 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1610 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1611 // Update filtering objective and L2IG group bucket
1612 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1613 } else {
1614 // RemoveVlanNative
1615 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1616 }
1617 }
1618
1619 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1620 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1621 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1622 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1623 // Update filtering objective and L2IG group bucket
1624 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1625 } else {
1626 // RemoveVlanUntagged
1627 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1628 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001629 }
1630
1631 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1632 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001633 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1634 .filter(i -> !intf.vlanUntagged().equals(i))
1635 .filter(i -> !intf.vlanNative().equals(i))
1636 .forEach(vlanId -> updateVlanConfigInternal(
1637 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001638 }
1639
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001640 if (!intf.vlanNative().equals(VlanId.NONE)
1641 && !prevIntf.vlanNative().equals(intf.vlanNative())
1642 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1643 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1644 // Update filtering objective and L2IG group bucket
1645 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1646 } else {
1647 // AddVlanNative
1648 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1649 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001650 }
1651
1652 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1653 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001654 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1655 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1656 .filter(i -> !prevIntf.vlanNative().equals(i))
1657 .forEach(vlanId -> updateVlanConfigInternal(
1658 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001659 );
1660 }
1661
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001662 if (!intf.vlanUntagged().equals(VlanId.NONE)
1663 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1664 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1665 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1666 // Update filtering objective and L2IG group bucket
1667 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1668 } else {
1669 // AddVlanUntagged
1670 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1671 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001672 }
1673 addSubnetConfig(prevIntf.connectPoint(),
1674 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1675 new HashSet<>(prevIntf.ipAddressesList())));
1676 } catch (ConfigException e) {
1677 log.error("Error in configuration");
1678 }
1679 }
1680
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001681 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1682 VlanId vlanId, boolean pushVlan) {
1683 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1684 if (grpHandler == null) {
1685 log.warn("Failed to retrieve group handler for device {}", deviceId);
1686 return;
1687 }
1688
1689 // Update filtering objective for a single port
1690 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1691 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1692
1693 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1694 // Update L2IG bucket of the port
1695 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1696 } else {
1697 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1698 }
1699 }
1700
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001701 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1702 VlanId vlanId, boolean pushVlan, boolean install) {
1703 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1704 if (grpHandler == null) {
1705 log.warn("Failed to retrieve group handler for device {}", deviceId);
1706 return;
1707 }
1708
1709 // Update filtering objective for a single port
1710 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1711
1712 // Update filtering objective for multicast ingress port
1713 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1714
1715 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1716
1717 if (nextId != -1 && !install) {
1718 // Update next objective for a single port as an output port
1719 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001720 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001721 // Remove L2 Bridging rule and L3 Unicast rule to the host
1722 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1723 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1724 // only if there is no port configured on that VLAN ID
1725 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1726 // Remove broadcast forwarding rule for the VLAN
1727 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1728 // Remove L2FG for VLAN
1729 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1730 } else {
1731 // Remove L2IG of the port
1732 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1733 }
1734 } else if (install) {
1735 if (nextId != -1) {
1736 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001737 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001738 } else {
1739 // Create L2FG for VLAN
1740 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1741 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1742 }
1743 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1744 } else {
1745 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1746 }
1747 }
1748
1749 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1750 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1751 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1752
1753 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1754 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1755 .filter(intf -> !intf.connectPoint().equals(cp))
1756 .flatMap(intf -> intf.ipAddressesList().stream())
1757 .collect(Collectors.toSet());
1758 // 1. Partial subnet population
1759 // Remove routing rules for removed subnet from previous configuration,
1760 // which does not also exist in other interfaces in the same device
1761 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1762 .map(InterfaceIpAddress::subnetAddress)
1763 .collect(Collectors.toSet());
1764
1765 defaultRoutingHandler.revokeSubnet(
1766 ipPrefixSet.stream()
1767 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1768 .collect(Collectors.toSet()));
1769
1770 // 2. Interface IP punts
1771 // Remove IP punts for old Intf address
1772 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1773 .map(InterfaceIpAddress::ipAddress)
1774 .collect(Collectors.toSet());
1775 ipAddressSet.stream()
1776 .map(InterfaceIpAddress::ipAddress)
1777 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1778 .forEach(interfaceIpAddress ->
1779 routingRulePopulator.revokeSingleIpPunts(
1780 cp.deviceId(), interfaceIpAddress));
1781
1782 // 3. Host unicast routing rule
1783 // Remove unicast routing rule
1784 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1785 }
1786
1787 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1788 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1789 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1790
1791 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1792 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1793 .filter(intf -> !intf.connectPoint().equals(cp))
1794 .flatMap(intf -> intf.ipAddressesList().stream())
1795 .collect(Collectors.toSet());
1796 // 1. Partial subnet population
1797 // Add routing rules for newly added subnet, which does not also exist in
1798 // other interfaces in the same device
1799 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1800 .map(InterfaceIpAddress::subnetAddress)
1801 .collect(Collectors.toSet());
1802
1803 defaultRoutingHandler.populateSubnet(
1804 Collections.singleton(cp),
1805 ipPrefixSet.stream()
1806 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1807 .collect(Collectors.toSet()));
1808
1809 // 2. Interface IP punts
1810 // Add IP punts for new Intf address
1811 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1812 .map(InterfaceIpAddress::ipAddress)
1813 .collect(Collectors.toSet());
1814 ipAddressSet.stream()
1815 .map(InterfaceIpAddress::ipAddress)
1816 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1817 .forEach(interfaceIpAddress ->
1818 routingRulePopulator.populateSingleIpPunts(
1819 cp.deviceId(), interfaceIpAddress));
1820
1821 // 3. Host unicast routing rule
1822 // Add unicast routing rule
1823 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1824 }
sanghob35a6192015-04-01 13:05:26 -07001825}