blob: f955857881df91d7053bb416aa841446e27e5c58 [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
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070018import java.util.Collections;
Charles Chanba90df12017-11-30 15:37:50 -080019import java.util.Dictionary;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070020import java.util.HashSet;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070021import java.util.List;
22import java.util.Map;
23import java.util.Map.Entry;
24import java.util.Optional;
25import java.util.Set;
26import java.util.concurrent.ConcurrentHashMap;
27import java.util.concurrent.ConcurrentLinkedQueue;
28import java.util.concurrent.Executors;
29import java.util.concurrent.ScheduledExecutorService;
30import java.util.concurrent.ScheduledFuture;
31import java.util.concurrent.TimeUnit;
32import java.util.concurrent.atomic.AtomicBoolean;
33import java.util.stream.Collectors;
34
Charles Chanb15d0102017-08-23 13:55:39 -070035import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070036import org.apache.felix.scr.annotations.Activate;
37import org.apache.felix.scr.annotations.Component;
38import org.apache.felix.scr.annotations.Deactivate;
Charles Chanba90df12017-11-30 15:37:50 -080039import org.apache.felix.scr.annotations.Modified;
40import org.apache.felix.scr.annotations.Property;
sanghob35a6192015-04-01 13:05:26 -070041import org.apache.felix.scr.annotations.Reference;
42import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070043import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070044import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080045import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070046import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080047import org.onlab.packet.IPv6;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070048import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070049import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070050import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070051import org.onlab.util.KryoNamespace;
Charles Chanba90df12017-11-30 15:37:50 -080052import org.onlab.util.Tools;
Saurav Das80980c72016-03-23 11:22:49 -070053import org.onosproject.cfg.ComponentConfigService;
sanghob35a6192015-04-01 13:05:26 -070054import org.onosproject.core.ApplicationId;
55import org.onosproject.core.CoreService;
56import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070057import org.onosproject.mastership.MastershipService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080058import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070059import org.onosproject.net.Device;
60import org.onosproject.net.DeviceId;
Charles Chanb15d0102017-08-23 13:55:39 -070061import org.onosproject.net.Host;
62import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070063import org.onosproject.net.Link;
64import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080065import org.onosproject.net.PortNumber;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070066import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070067import org.onosproject.net.config.ConfigFactory;
68import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070069import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070070import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070071import org.onosproject.net.config.basics.InterfaceConfig;
72import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070073import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070074import org.onosproject.net.device.DeviceEvent;
75import org.onosproject.net.device.DeviceListener;
76import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080077import org.onosproject.net.flow.TrafficSelector;
78import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070079import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080080import org.onosproject.net.host.HostEvent;
81import org.onosproject.net.host.HostListener;
Charles Chanba90df12017-11-30 15:37:50 -080082import org.onosproject.net.host.HostLocationProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080083import org.onosproject.net.host.HostService;
Jonghwan Hyun5f1def82017-08-25 17:48:36 -070084import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070085import org.onosproject.net.intf.Interface;
86import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080087import org.onosproject.net.link.LinkEvent;
88import org.onosproject.net.link.LinkListener;
89import org.onosproject.net.link.LinkService;
Charles Chand55e84d2016-03-30 17:54:24 -070090import org.onosproject.net.mcast.McastEvent;
91import org.onosproject.net.mcast.McastListener;
92import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070093import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080094import org.onosproject.net.packet.InboundPacket;
95import org.onosproject.net.packet.PacketContext;
96import org.onosproject.net.packet.PacketProcessor;
97import org.onosproject.net.packet.PacketService;
Pier Ventre42287df2016-11-09 14:17:26 -080098import org.onosproject.net.topology.PathService;
Charles Chand55e84d2016-03-30 17:54:24 -070099import org.onosproject.net.topology.TopologyService;
Charles Chanb15d0102017-08-23 13:55:39 -0700100import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700101import org.onosproject.routeservice.RouteEvent;
102import org.onosproject.routeservice.RouteListener;
103import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700104import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
105import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800106import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventref34966c2016-11-07 16:21:04 -0800107import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700108import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700109import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700110import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700111import org.onosproject.segmentrouting.grouphandler.DestinationSet;
112import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700113import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700114import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700115import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800116import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700117import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700118import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700119import org.onosproject.store.service.EventuallyConsistentMap;
120import org.onosproject.store.service.EventuallyConsistentMapBuilder;
121import org.onosproject.store.service.StorageService;
122import org.onosproject.store.service.WallClockTimestamp;
Charles Chanba90df12017-11-30 15:37:50 -0800123import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700124import org.slf4j.Logger;
125import org.slf4j.LoggerFactory;
126
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700127import com.google.common.collect.HashMultimap;
128import com.google.common.collect.ImmutableMap;
129import com.google.common.collect.Maps;
130import com.google.common.collect.Multimap;
sanghob35a6192015-04-01 13:05:26 -0700131
Charles Chan3e783d02016-02-26 22:19:52 -0800132import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800133import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700134import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800135
Charles Chane849c192016-01-11 18:28:54 -0800136/**
137 * Segment routing manager.
138 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700139@Service
140@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700141public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700142
Charles Chan2c15aca2016-11-09 20:51:44 -0800143 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan23686832017-08-23 14:46:43 -0700144 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700147 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800150 private NeighbourResolutionService neighbourResolutionService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800153 public PathService pathService;
154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700156 CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700159 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700162 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanba90df12017-11-30 15:37:50 -0800165 HostLocationProbingService probingService;
166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700168 DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700169
170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800171 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700174 LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700175
Charles Chan5270ed02016-01-30 23:22:37 -0800176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800177 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800180 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
183 MulticastRouteService multicastRouteService;
184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
186 TopologyService topologyService;
187
188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700189 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800190
191 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800192 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800193
Saurav Das80980c72016-03-23 11:22:49 -0700194 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800195 public InterfaceService interfaceService;
196
Charles Chanba90df12017-11-30 15:37:50 -0800197 @Property(name = "activeProbing", boolValue = true,
198 label = "Enable active probing to discover dual-homed hosts.")
199 boolean activeProbing = true;
200
Charles Chan03a73e02016-10-24 14:52:01 -0700201 ArpHandler arpHandler = null;
202 IcmpHandler icmpHandler = null;
203 IpHandler ipHandler = null;
204 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700205 ApplicationId appId;
206 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700207
Charles Chan03a73e02016-10-24 14:52:01 -0700208 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700209 private TunnelHandler tunnelHandler = null;
210 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700211 private InternalPacketProcessor processor = null;
212 private InternalLinkListener linkListener = null;
213 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700214 private AppConfigHandler appCfgHandler = null;
Charles Chan03a73e02016-10-24 14:52:01 -0700215 XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700216 private McastHandler mcastHandler = null;
Charles Chan65238242017-06-22 18:03:14 -0700217 private HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800218 private RouteHandler routeHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800219 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventref34966c2016-11-07 16:21:04 -0800220 private L2TunnelHandler l2TunnelHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700221 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800222 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700223 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
224 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700225 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sanghob35a6192015-04-01 13:05:26 -0700226
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700227 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700228 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700229
Saurav Das4ce45962015-11-24 23:21:05 -0800230 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700231 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800232 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700233 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800234 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800235 new ConcurrentHashMap<>();
236 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700237 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5deb3232017-08-22 15:07:34 -0700238 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800239 */
Charles Chanba90df12017-11-30 15:37:50 -0800240 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700241 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800242 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700243 * Per device next objective ID store with (device id + vlanid) as key.
244 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800245 */
Charles Chanba90df12017-11-30 15:37:50 -0800246 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800247 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800248 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700249 * Per device next objective ID store with (device id + port + treatment + meta) as key.
250 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800251 */
Charles Chanba90df12017-11-30 15:37:50 -0800252 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800253 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800254
Saurav Dasc88d4662017-05-15 15:34:25 -0700255 // Local store for all links seen and their present status, used for
256 // optimized routing. The existence of the link in the keys is enough to know
257 // if the link has been "seen-before" by this instance of the controller.
258 // The boolean value indicates if the link is currently up or not.
259 // XXX Currently the optimized routing logic depends on "forgetting" a link
260 // when a switch goes down, but "remembering" it when only the link goes down.
261 // Consider changing this logic so we can use the Link Service instead of
262 // a local cache.
263 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
264
Saurav Das4ce45962015-11-24 23:21:05 -0800265 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
266 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700267
Saurav Das7bcbe702017-06-13 15:35:54 -0700268 private AtomicBoolean programmingScheduled = new AtomicBoolean();
269
Charles Chand55e84d2016-03-30 17:54:24 -0700270 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700271 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
272 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700273 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700274 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800275 public SegmentRoutingDeviceConfig createConfig() {
276 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700277 }
278 };
Pier Ventref34966c2016-11-07 16:21:04 -0800279
Charles Chand55e84d2016-03-30 17:54:24 -0700280 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700281 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
282 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700283 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800284 @Override
285 public SegmentRoutingAppConfig createConfig() {
286 return new SegmentRoutingAppConfig();
287 }
288 };
Pier Ventref34966c2016-11-07 16:21:04 -0800289
Charles Chanfc5c7802016-05-17 13:13:55 -0700290 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
291 new ConfigFactory<ApplicationId, XConnectConfig>(
292 SubjectFactories.APP_SUBJECT_FACTORY,
293 XConnectConfig.class, "xconnect") {
294 @Override
295 public XConnectConfig createConfig() {
296 return new XConnectConfig();
297 }
298 };
Pier Ventref34966c2016-11-07 16:21:04 -0800299
Charles Chand55e84d2016-03-30 17:54:24 -0700300 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700301 new ConfigFactory<ApplicationId, McastConfig>(
302 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700303 McastConfig.class, "multicast") {
304 @Override
305 public McastConfig createConfig() {
306 return new McastConfig();
307 }
308 };
309
Pier Ventref34966c2016-11-07 16:21:04 -0800310 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
311 new ConfigFactory<ApplicationId, PwaasConfig>(
312 SubjectFactories.APP_SUBJECT_FACTORY,
313 PwaasConfig.class, "pwaas") {
314 @Override
315 public PwaasConfig createConfig() {
316 return new PwaasConfig();
317 }
318 };
319
Charles Chan65238242017-06-22 18:03:14 -0700320 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700321 private static int numOfEventsQueued = 0;
322 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700323 private static int numOfHandlerExecution = 0;
324 private static int numOfHandlerScheduled = 0;
325
Charles Chan116188d2016-02-18 14:22:42 -0800326 /**
327 * Segment Routing App ID.
328 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800329 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800330
Charles Chane849c192016-01-11 18:28:54 -0800331 /**
332 * The default VLAN ID assigned to the interfaces without subnet config.
333 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800334 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700335
sanghob35a6192015-04-01 13:05:26 -0700336 @Activate
Charles Chanba90df12017-11-30 15:37:50 -0800337 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800338 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700339
340 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700341 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700342 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700343 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700344 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700345 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700346 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700347 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700348 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700349
Charles Chan59cc16d2017-02-02 16:20:42 -0800350 log.debug("Creating EC map vlannextobjectivestore");
351 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
352 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
353 vlanNextObjStore = vlanNextObjMapBuilder
354 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700355 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700356 .withTimestampProvider((k, v) -> new WallClockTimestamp())
357 .build();
358
Saurav Das4ce45962015-11-24 23:21:05 -0800359 log.debug("Creating EC map subnetnextobjectivestore");
360 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
361 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
362 portNextObjStore = portNextObjMapBuilder
363 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700364 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800365 .withTimestampProvider((k, v) -> new WallClockTimestamp())
366 .build();
367
sangho0b2b6d12015-05-20 22:16:38 -0700368 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
369 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700370 tunnelStore = tunnelMapBuilder
371 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700372 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700373 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700374 .build();
375
376 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
377 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700378 policyStore = policyMapBuilder
379 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700380 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700381 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700382 .build();
383
Saurav Das80980c72016-03-23 11:22:49 -0700384 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800385 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700386 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800387 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800388 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
389 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700390 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800391 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700392 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800393 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800394 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
395 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800396 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
397 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700398 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700399 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700400 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
401 "multihomingEnabled", "true");
Charles Chanfd892012017-11-29 19:54:20 -0800402 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
403 "staleLinkAge", "15000");
404 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
405 "allowDuplicateIps", "false");
Charles Chanba90df12017-11-30 15:37:50 -0800406 compCfgService.registerProperties(getClass());
407 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700408
Charles Chanb8e10c82015-10-14 11:24:40 -0700409 processor = new InternalPacketProcessor();
410 linkListener = new InternalLinkListener();
411 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700412 appCfgHandler = new AppConfigHandler(this);
413 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700414 mcastHandler = new McastHandler(this);
415 hostHandler = new HostHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700416 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800417 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventref34966c2016-11-07 16:21:04 -0800418 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700419
Charles Chan3e783d02016-02-26 22:19:52 -0800420 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700421 cfgService.registerConfigFactory(deviceConfigFactory);
422 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700423 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700424 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800425 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800426 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700427 packetService.addProcessor(processor, PacketProcessor.director(2));
428 linkService.addListener(linkListener);
429 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700430 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700431 routeService.addListener(routeListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700432
433 cfgListener.configureNetwork();
434
sanghob35a6192015-04-01 13:05:26 -0700435 log.info("Started");
436 }
437
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700438 private KryoNamespace.Builder createSerializer() {
439 return new KryoNamespace.Builder()
440 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700441 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan59cc16d2017-02-02 16:20:42 -0800442 VlanNextObjectiveStoreKey.class,
Saurav Das7bcbe702017-06-13 15:35:54 -0700443 DestinationSet.class,
444 NextNeighbors.class,
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700445 Tunnel.class,
446 DefaultTunnel.class,
447 Policy.class,
448 TunnelPolicy.class,
449 Policy.Type.class,
450 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700451 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700452 );
453 }
454
sanghob35a6192015-04-01 13:05:26 -0700455 @Deactivate
456 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700457 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700458 cfgService.unregisterConfigFactory(deviceConfigFactory);
459 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700460 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700461 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800462 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chanba90df12017-11-30 15:37:50 -0800463 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700464
Charles Chanc7a8a682017-06-19 00:43:31 -0700465 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700466 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700467 linkService.removeListener(linkListener);
468 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700469 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700470 routeService.removeListener(routeListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700471
Charles Chan0aa674e2017-02-23 15:44:08 -0800472 neighbourResolutionService.unregisterNeighbourHandlers(appId);
473
sanghob35a6192015-04-01 13:05:26 -0700474 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700475 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700476 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700477 groupHandlerMap.clear();
478
Saurav Das7bcbe702017-06-13 15:35:54 -0700479 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800480 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700481 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700482 tunnelStore.destroy();
483 policyStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700484 log.info("Stopped");
485 }
486
Charles Chanba90df12017-11-30 15:37:50 -0800487 @Modified
488 private void modified(ComponentContext context) {
489 Dictionary<?, ?> properties = context.getProperties();
490 if (properties == null) {
491 return;
492 }
493
494 String strActiveProving = Tools.get(properties, "activeProbing");
495 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
496
497 if (expectActiveProbing != activeProbing) {
498 activeProbing = expectActiveProbing;
499 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
500 }
501 }
502
sangho1e575652015-05-14 00:39:53 -0700503 @Override
504 public List<Tunnel> getTunnels() {
505 return tunnelHandler.getTunnels();
506 }
507
508 @Override
sangho71abe1b2015-06-29 14:58:47 -0700509 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
510 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700511 }
512
513 @Override
sangho71abe1b2015-06-29 14:58:47 -0700514 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700515 for (Policy policy: policyHandler.getPolicies()) {
516 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
517 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
518 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
519 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700520 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700521 }
522 }
523 }
sangho71abe1b2015-06-29 14:58:47 -0700524 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700525 }
526
527 @Override
sangho71abe1b2015-06-29 14:58:47 -0700528 public PolicyHandler.Result removePolicy(Policy policy) {
529 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700530 }
531
532 @Override
sangho71abe1b2015-06-29 14:58:47 -0700533 public PolicyHandler.Result createPolicy(Policy policy) {
534 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700535 }
536
537 @Override
538 public List<Policy> getPolicies() {
539 return policyHandler.getPolicies();
540 }
541
Saurav Das59232cf2016-04-27 18:35:50 -0700542 @Override
543 public void rerouteNetwork() {
544 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700545 }
546
Charles Chanc81c45b2016-10-20 17:02:44 -0700547 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800548 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
549 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chanc81c45b2016-10-20 17:02:44 -0700550 deviceService.getAvailableDevices().forEach(device -> {
551 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
552 });
553 return deviceSubnetMap;
554 }
555
Saurav Dasc88d4662017-05-15 15:34:25 -0700556
557 @Override
558 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
559 if (defaultRoutingHandler != null) {
560 return defaultRoutingHandler.getCurrentEmcpSpgMap();
561 } else {
562 return null;
563 }
564 }
565
566 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700567 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
568 if (dsNextObjStore != null) {
569 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700570 } else {
571 return ImmutableMap.of();
572 }
573 }
574
Saurav Dasceccf242017-08-03 18:30:35 -0700575 @Override
576 public void verifyGroups(DeviceId id) {
577 DefaultGroupHandler gh = groupHandlerMap.get(id);
578 if (gh != null) {
579 gh.triggerBucketCorrector();
580 }
581 }
582
sanghof9d0bf12015-05-19 11:57:42 -0700583 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700584 * Extracts the application ID from the manager.
585 *
586 * @return application ID
587 */
588 public ApplicationId appId() {
589 return appId;
590 }
591
592 /**
593 * Returns the device configuration.
594 *
595 * @return device configuration
596 */
597 public DeviceConfiguration deviceConfiguration() {
598 return deviceConfiguration;
599 }
600
601 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700602 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5deb3232017-08-22 15:07:34 -0700603 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700604 *
605 * @return next objective ID store
606 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700607 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
608 dsNextObjStore() {
609 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700610 }
611
612 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700613 * Per device next objective ID store with (device id + vlanid) as key.
614 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700615 *
616 * @return vlan next object store
617 */
618 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
619 return vlanNextObjStore;
620 }
621
622 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700623 * Per device next objective ID store with (device id + port + treatment + meta) as key.
624 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700625 *
626 * @return port next object store.
627 */
628 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
629 return portNextObjStore;
630 }
631
632 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700633 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
634 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700635 *
636 * @return MPLS-ECMP value
637 */
638 public boolean getMplsEcmp() {
639 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
640 .getConfig(this.appId, SegmentRoutingAppConfig.class);
641 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
642 }
643
644 /**
sanghof9d0bf12015-05-19 11:57:42 -0700645 * Returns the tunnel object with the tunnel ID.
646 *
647 * @param tunnelId Tunnel ID
648 * @return Tunnel reference
649 */
sangho1e575652015-05-14 00:39:53 -0700650 public Tunnel getTunnel(String tunnelId) {
651 return tunnelHandler.getTunnel(tunnelId);
652 }
653
Charles Chan7ffd81f2017-02-08 15:52:08 -0800654 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700655 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800656 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800657 * <p>
658 * Only returns the first match if there are multiple untagged VLAN configured
659 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700660 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800661 * @param connectPoint connect point
662 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700663 */
Charles Chan65238242017-06-22 18:03:14 -0700664 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800665 return interfaceService.getInterfacesByPort(connectPoint).stream()
666 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
667 .map(Interface::vlanUntagged)
668 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700669 }
670
sangho1e575652015-05-14 00:39:53 -0700671 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800672 * Returns tagged VLAN configured on given connect point.
673 * <p>
674 * Returns all matches if there are multiple tagged VLAN configured
675 * on the connect point.
676 *
677 * @param connectPoint connect point
678 * @return tagged VLAN or empty set if not configured
679 */
Charles Chan65238242017-06-22 18:03:14 -0700680 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800681 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
682 return interfaces.stream()
683 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700684 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800685 .collect(Collectors.toSet());
686 }
687
688 /**
689 * Returns native VLAN configured on given connect point.
690 * <p>
691 * Only returns the first match if there are multiple native VLAN configured
692 * on the connect point.
693 *
694 * @param connectPoint connect point
695 * @return native VLAN or null if not configured
696 */
Charles Chan65238242017-06-22 18:03:14 -0700697 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800698 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
699 return interfaces.stream()
700 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
701 .map(Interface::vlanNative)
702 .findFirst()
703 .orElse(null);
704 }
705
706 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700707 * Returns internal VLAN for untagged hosts on given connect point.
708 * <p>
709 * The internal VLAN is either vlan-untagged for an access port,
710 * or vlan-native for a trunk port.
711 *
712 * @param connectPoint connect point
713 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
714 */
Charles Chan65238242017-06-22 18:03:14 -0700715 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700716 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
717 VlanId nativeVlanId = getNativeVlanId(connectPoint);
718 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
719 }
720
721 /**
Charles Chan65238242017-06-22 18:03:14 -0700722 * Returns optional pair device ID of given device.
723 *
724 * @param deviceId device ID
725 * @return optional pair device ID. Might be empty if pair device is not configured
726 */
727 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
728 SegmentRoutingDeviceConfig deviceConfig =
729 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
730 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
731 }
732 /**
733 * Returns optional pair device local port of given device.
734 *
735 * @param deviceId device ID
736 * @return optional pair device ID. Might be empty if pair device is not configured
737 */
738 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
739 SegmentRoutingDeviceConfig deviceConfig =
740 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
741 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
742 }
743
744 /**
Charles Chan23686832017-08-23 14:46:43 -0700745 * Determine if current instance is the master of given connect point.
746 *
747 * @param cp connect point
748 * @return true if current instance is the master of given connect point
749 */
750 boolean isMasterOf(ConnectPoint cp) {
751 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
752 if (!isMaster) {
753 log.debug(NOT_MASTER, cp);
754 }
755 return isMaster;
756 }
757
758 /**
Charles Chanb15d0102017-08-23 13:55:39 -0700759 * Returns locations of given resolved route.
760 *
761 * @param resolvedRoute resolved route
762 * @return locations of nexthop. Might be empty if next hop is not found
763 */
764 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
765 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
766 return Optional.ofNullable(hostService.getHost(hostId))
767 .map(Host::locations).orElse(Sets.newHashSet())
768 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
769 }
770
771 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800772 * Returns vlan port map of given device.
773 *
774 * @param deviceId device id
775 * @return vlan-port multimap
776 */
777 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
778 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
779
780 interfaceService.getInterfaces().stream()
781 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
782 .forEach(intf -> {
783 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700784 intf.vlanTagged().forEach(vlanTagged ->
785 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
786 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800787 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
788 });
789 vlanPortMap.removeAll(VlanId.NONE);
790
791 return vlanPortMap;
792 }
793
794 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800795 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800796 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700797 *
798 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800799 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800800 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700801 */
Charles Chan65238242017-06-22 18:03:14 -0700802 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700803 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800804 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
805 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700806 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800807 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800808 + "device {} not found", deviceId);
809 return -1;
810 }
811 }
812
813 /**
814 * Returns the next objective ID for the given portNumber, given the treatment.
815 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700816 * would result in different objectives. If the next object does not exist,
817 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800818 *
819 * @param deviceId Device ID
820 * @param portNum port number on device for which NextObjective is queried
821 * @param treatment the actions to apply on the packets (should include outport)
822 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700823 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700824 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800825 */
826 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
827 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700828 TrafficSelector meta,
829 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800830 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
831 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700832 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800833 } else {
Charles Chane849c192016-01-11 18:28:54 -0800834 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
835 + " not found", deviceId);
836 return -1;
837 }
838 }
839
Saurav Dasc88d4662017-05-15 15:34:25 -0700840 /**
841 * Returns the group handler object for the specified device id.
842 *
843 * @param devId the device identifier
844 * @return the groupHandler object for the device id, or null if not found
845 */
Charles Chan65238242017-06-22 18:03:14 -0700846 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700847 return groupHandlerMap.get(devId);
848 }
849
850 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700851 * Returns the default routing handler object.
852 *
853 * @return the default routing handler object
854 */
855 public DefaultRoutingHandler getRoutingHandler() {
856 return defaultRoutingHandler;
857 }
858
859 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700860 * Returns true if this controller instance has seen this link before. The
861 * link may not be currently up, but as long as the link had been seen before
862 * this method will return true. The one exception is when the link was
863 * indeed seen before, but this controller instance was forced to forget it
864 * by a call to purgeSeenLink method.
865 *
866 * @param link the infrastructure link being queried
867 * @return true if this controller instance has seen this link before
868 */
Charles Chan65238242017-06-22 18:03:14 -0700869 boolean isSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700870 return seenLinks.containsKey(link);
871 }
872
873 /**
874 * Updates the seen link store. Updates can be for links that are currently
875 * available or not.
876 *
877 * @param link the link to update in the seen-link local store
878 * @param up the status of the link, true if up, false if down
879 */
Charles Chan65238242017-06-22 18:03:14 -0700880 void updateSeenLink(Link link, boolean up) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700881 seenLinks.put(link, up);
882 }
883
884 /**
885 * Returns the status of a seen-link (up or down). If the link has not
886 * been seen-before, a null object is returned.
887 *
888 * @param link the infrastructure link being queried
889 * @return null if the link was not seen-before;
890 * true if the seen-link is up;
891 * false if the seen-link is down
892 */
Charles Chanba90df12017-11-30 15:37:50 -0800893 private Boolean isSeenLinkUp(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700894 return seenLinks.get(link);
895 }
896
897 /**
898 * Makes this controller instance forget a previously seen before link.
899 *
900 * @param link the infrastructure link to purge
901 */
Charles Chan65238242017-06-22 18:03:14 -0700902 private void purgeSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700903 seenLinks.remove(link);
904 }
905
906 /**
907 * Returns the status of a link as parallel link. A parallel link
908 * is defined as a link which has common src and dst switches as another
909 * seen-link that is currently enabled. It is not necessary for the link being
910 * queried to be a seen-link.
911 *
912 * @param link the infrastructure link being queried
913 * @return true if a seen-link exists that is up, and shares the
914 * same src and dst switches as the link being queried
915 */
Charles Chan65238242017-06-22 18:03:14 -0700916 private boolean isParallelLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700917 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
918 Link seenLink = seen.getKey();
919 if (seenLink.equals(link)) {
920 continue;
921 }
922 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
923 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
924 seen.getValue()) {
925 return true;
926 }
927 }
928 return false;
929 }
930
Saurav Das7bcbe702017-06-13 15:35:54 -0700931 /**
932 * Returns true if the link being queried is a bidirectional link. A bidi
933 * link is defined as a link, whose reverse link - ie. the link in the reverse
934 * direction - has been seen-before and is up. It is not necessary for the link
935 * being queried to be a seen-link.
936 *
937 * @param link the infrastructure link being queried
938 * @return true if another unidirectional link exists in the reverse direction,
939 * has been seen-before and is up
940 */
Charles Chanba90df12017-11-30 15:37:50 -0800941 boolean isBidirectional(Link link) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700942 Link reverseLink = linkService.getLink(link.dst(), link.src());
943 if (reverseLink == null) {
944 return false;
945 }
946 Boolean result = isSeenLinkUp(reverseLink);
947 if (result == null) {
948 return false;
949 }
950 return result.booleanValue();
951 }
952
953 /**
954 * Determines if the given link should be avoided in routing calculations
955 * by policy or design.
956 *
957 * @param link the infrastructure link being queried
958 * @return true if link should be avoided
959 */
Charles Chanba90df12017-11-30 15:37:50 -0800960 boolean avoidLink(Link link) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700961 // XXX currently only avoids all pair-links. In the future can be
962 // extended to avoid any generic link
963 DeviceId src = link.src().deviceId();
964 PortNumber srcPort = link.src().port();
965 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
966 log.warn("Device {} not configured..cannot avoid link {}", src, link);
967 return false;
968 }
969 DeviceId pairDev;
970 PortNumber pairLocalPort, pairRemotePort = null;
971 try {
972 pairDev = deviceConfiguration.getPairDeviceId(src);
973 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
974 if (pairDev != null) {
975 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
976 }
977 } catch (DeviceConfigNotFoundException e) {
978 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
979 src, link);
980 return false;
981 }
982
Charles Chanba90df12017-11-30 15:37:50 -0800983 return srcPort.equals(pairLocalPort) &&
Saurav Das7bcbe702017-06-13 15:35:54 -0700984 link.dst().deviceId().equals(pairDev) &&
Charles Chanba90df12017-11-30 15:37:50 -0800985 link.dst().port().equals(pairRemotePort);
Saurav Das7bcbe702017-06-13 15:35:54 -0700986 }
987
sanghob35a6192015-04-01 13:05:26 -0700988 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700989 @Override
990 public void process(PacketContext context) {
991
992 if (context.isHandled()) {
993 return;
994 }
995
996 InboundPacket pkt = context.inPacket();
997 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -0800998
999 if (ethernet == null) {
1000 return;
1001 }
1002
Saurav Das7bcbe702017-06-13 15:35:54 -07001003 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1004 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001005 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001006 log.warn("Received unexpected ARP packet on {}",
1007 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001008 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001009 return;
sanghob35a6192015-04-01 13:05:26 -07001010 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001011 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1012 //ipHandler.addToPacketBuffer(ipv4Packet);
1013 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1014 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001015 } else {
Charles Chan50035632017-01-13 17:20:44 -08001016 // NOTE: We don't support IP learning at this moment so this
1017 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001018 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001019 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001020 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1021 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001022 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001023 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001024 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1025 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1026 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1027 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1028 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1029 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001030 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001031 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001032 }
1033 } else {
1034 // NOTE: We don't support IP learning at this moment so this
1035 // is not necessary. Also it causes duplication of DHCPv6 packets.
1036 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1037 }
sanghob35a6192015-04-01 13:05:26 -07001038 }
1039 }
1040 }
1041
1042 private class InternalLinkListener implements LinkListener {
1043 @Override
1044 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001045 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1046 event.type() == LinkEvent.Type.LINK_UPDATED ||
1047 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001048 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001049 scheduleEventHandlerIfNotScheduled(event);
1050 }
1051 }
1052 }
1053
1054 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001055 @Override
1056 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001057 switch (event.type()) {
1058 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001059 case PORT_UPDATED:
1060 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001061 case DEVICE_UPDATED:
1062 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001063 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001064 scheduleEventHandlerIfNotScheduled(event);
1065 break;
1066 default:
1067 }
1068 }
1069 }
1070
Saurav Das4ce45962015-11-24 23:21:05 -08001071 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001072 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001073 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001074 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001075 numOfEventsQueued++;
1076
1077 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1078 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001079 eventHandlerFuture = executorService
1080 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1081 numOfHandlerScheduled++;
1082 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001083 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001084 numOfEventsQueued,
1085 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001086 }
sanghob35a6192015-04-01 13:05:26 -07001087 }
1088
1089 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001090 @Override
sanghob35a6192015-04-01 13:05:26 -07001091 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001092 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001093 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -08001094 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001095 Event event;
1096 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001097 if (!eventQueue.isEmpty()) {
1098 event = eventQueue.poll();
1099 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001100 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001101 numOfHandlerExecution++;
1102 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1103 numOfHandlerExecution, numOfEventsExecuted);
1104 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001105 }
sangho20eff1d2015-04-13 15:15:58 -07001106 }
Charles Chanb1f8c762017-03-29 16:39:05 -07001107 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1108 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001109 // Note: do not update seenLinks here, otherwise every
1110 // link, even one seen for the first time, will be appear
1111 // to be a previously seen link
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001112 processLinkAdded((Link) event.subject());
1113 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -07001114 Link linkRemoved = (Link) event.subject();
Saurav Dasc88d4662017-05-15 15:34:25 -07001115 if (linkRemoved.type() == Link.Type.DIRECT) {
1116 updateSeenLink(linkRemoved, false);
1117 }
1118 // device availability check helps to ensure that
1119 // multiple link-removed events are actually treated as a
1120 // single switch removed event. purgeSeenLink is necessary
1121 // so we do rerouting (instead of rehashing) when switch
1122 // comes back.
Pier Ventre2c515312016-09-13 21:33:40 -07001123 if (linkRemoved.src().elementId() instanceof DeviceId &&
1124 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001125 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001126 continue;
1127 }
1128 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1129 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001130 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001131 continue;
1132 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001133 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001134 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1135 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1136 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001137 DeviceId deviceId = ((Device) event.subject()).id();
1138 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001139 log.info("Processing device event {} for available device {}",
1140 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001141 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001142 } else {
1143 log.info("Processing device event {} for unavailable device {}",
1144 event.type(), ((Device) event.subject()).id());
1145 processDeviceRemoved((Device) event.subject());
1146 }
Saurav Das1a129a02016-11-18 15:21:57 -08001147 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001148 // typically these calls come when device is added first time
1149 // so port filtering rules are handled at the device_added event.
1150 // port added calls represent all ports on the device,
1151 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001152 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001153 ((DeviceEvent) event).subject().id(),
1154 ((DeviceEvent) event).port().number(),
1155 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001156 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001157 // these calls happen for every subsequent event
1158 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001159 log.info("** PORT UPDATED {}/{} -> {}",
1160 event.subject(),
1161 ((DeviceEvent) event).port(),
1162 event.type());
1163 processPortUpdated(((Device) event.subject()),
1164 ((DeviceEvent) event).port());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001165 } else {
1166 log.warn("Unhandled event type: {}", event.type());
1167 }
sanghob35a6192015-04-01 13:05:26 -07001168 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001169 } catch (Exception e) {
1170 log.error("SegmentRouting event handler "
1171 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -07001172 }
sanghob35a6192015-04-01 13:05:26 -07001173 }
1174 }
1175
sanghob35a6192015-04-01 13:05:26 -07001176 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001177 log.info("** LINK ADDED {}", link.toString());
Saurav Das92f01e12017-12-19 16:08:42 -08001178 if (!isLinkValid(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001179 return;
1180 }
Saurav Das041bb782017-08-14 16:44:43 -07001181 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1182 updateSeenLink(link, true);
1183 // XXX revisit - what about devicePortMap
1184 log.warn("Source device of this link is not configured.. "
1185 + "not processing further");
1186 return;
1187 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001188
1189 //Irrespective of whether the local is a MASTER or not for this device,
1190 //create group handler instance and push default TTP flow rules if needed,
1191 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001192 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1193 .deviceId());
1194 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001195 groupHandler.portUpForLink(link);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001196 } else {
Saurav Das041bb782017-08-14 16:44:43 -07001197 // XXX revisit/cleanup
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001198 Device device = deviceService.getDevice(link.src().deviceId());
1199 if (device != null) {
1200 log.warn("processLinkAdded: Link Added "
1201 + "Notification without Device Added "
1202 + "event, still handling it");
1203 processDeviceAdded(device);
1204 groupHandler = groupHandlerMap.get(link.src()
1205 .deviceId());
Saurav Dasc88d4662017-05-15 15:34:25 -07001206 groupHandler.portUpForLink(link);
sanghob35a6192015-04-01 13:05:26 -07001207 }
1208 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001209
Saurav Das7bcbe702017-06-13 15:35:54 -07001210 /*// process link only if it is bidirectional
1211 if (!isBidirectional(link)) {
1212 log.debug("Link not bidirectional.. waiting for other direction "
1213 + "src {} --> dst {} ", link.dst(), link.src());
1214 // note that if we are not processing for routing, it should at least
1215 // be considered a seen-link
1216 updateSeenLink(link, true);
1217 return;
1218 }
1219 TO DO this ensure that rehash is still done correctly even if link is
1220 not processed for rerouting - perhaps rehash in both directions when
1221 it ultimately becomes bidi?
1222 */
1223
1224 log.debug("Starting optimized route population process for link "
1225 + "{} --> {}", link.src(), link.dst());
Saurav Dasc88d4662017-05-15 15:34:25 -07001226 boolean seenBefore = isSeenLink(link);
1227 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das7bcbe702017-06-13 15:35:54 -07001228
1229 // It's possible that linkUp causes no route-path change as ECMP graph does
1230 // not change if the link is a parallel link (same src-dst as another link.
1231 // However we still need to update ECMP hash groups to include new buckets
1232 // for the link that has come up.
Saurav Dasc88d4662017-05-15 15:34:25 -07001233 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001234 if (!seenBefore && isParallelLink(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001235 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das7bcbe702017-06-13 15:35:54 -07001236 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001237 groupHandler.retryHash(link, false, true);
1238 } else {
1239 //seen before-link
1240 if (isParallelLink(link)) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001241 log.debug("Attempting retryHash for paralled seen-before "
1242 + "link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001243 groupHandler.retryHash(link, false, false);
1244 }
1245 }
1246 }
Charles Chan2199c302016-04-23 17:36:10 -07001247
1248 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -07001249 }
1250
1251 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001252 log.info("** LINK REMOVED {}", link.toString());
Saurav Das92f01e12017-12-19 16:08:42 -08001253 if (!isLinkValid(link)) {
1254 return;
1255 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001256 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1257
1258 // update local groupHandler stores
sangho834e4b02015-05-01 09:38:25 -07001259 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1260 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001261 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1262 isParallelLink(link)) {
Saurav Das041bb782017-08-14 16:44:43 -07001263 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001264 groupHandler.retryHash(link, true, false);
Saurav Das041bb782017-08-14 16:44:43 -07001265 } else {
1266 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1267 (mastershipService.isLocalMaster(link.src().deviceId()))
1268 ? "not parallel" : "not master");
Saurav Dasc88d4662017-05-15 15:34:25 -07001269 }
1270 // ensure local stores are updated
1271 groupHandler.portDown(link.src().port());
1272 } else {
1273 log.warn("group handler not found for dev:{} when removing link: {}",
1274 link.src().deviceId(), link);
sangho834e4b02015-05-01 09:38:25 -07001275 }
Charles Chan2199c302016-04-23 17:36:10 -07001276
1277 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -07001278 }
1279
Saurav Das92f01e12017-12-19 16:08:42 -08001280 private boolean isLinkValid(Link link) {
1281 if (link.type() != Link.Type.DIRECT) {
1282 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1283 // if BDDP is received before LLDP. We can safely ignore that
1284 // until the LLDP is received and the link is marked as DIRECT.
1285 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1286 link.src(), link.dst(), link.type());
1287 return false;
1288 }
1289 DeviceId srcId = link.src().deviceId();
1290 DeviceId dstId = link.dst().deviceId();
1291 if (srcId.equals(dstId)) {
1292 log.warn("Links between ports on the same switch are not "
1293 + "allowed .. ignoring link {}", link);
1294 return false;
1295 }
1296 try {
1297 if (!deviceConfiguration.isEdgeDevice(srcId)
1298 && !deviceConfiguration.isEdgeDevice(dstId)) {
1299 // ignore links between spines
1300 // XXX revisit when handling multi-stage fabrics
1301 log.warn("Links between spines not allowed...ignoring "
1302 + "link {}", link);
1303 return false;
1304 }
1305 if (deviceConfiguration.isEdgeDevice(srcId)
1306 && deviceConfiguration.isEdgeDevice(dstId)) {
1307 // ignore links between leaves if they are not pair-links
1308 // XXX revisit if removing pair-link config or allowing more than
1309 // one pair-link
1310 if (deviceConfiguration.getPairDeviceId(srcId).equals(dstId)
1311 && deviceConfiguration.getPairLocalPort(srcId)
1312 .equals(link.src().port())
1313 && deviceConfiguration.getPairLocalPort(dstId)
1314 .equals(link.dst().port())) {
1315 // found pair link - allow it
1316 return true;
1317 } else {
1318 log.warn("Links between leaves other than pair-links are "
1319 + "not allowed...ignoring link {}", link);
1320 return false;
1321 }
1322 }
1323 } catch (DeviceConfigNotFoundException e) {
1324 // We still want to count the links in seenLinks even though there
1325 // is no config. So we let it return true
1326 log.warn("Could not check validity of link {} as subtending devices "
1327 + "are not yet configured", link);
1328 }
1329 return true;
1330 }
1331
sanghob35a6192015-04-01 13:05:26 -07001332 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001333 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001334
1335 // NOTE: Punt ARP/NDP even when the device is not configured.
1336 // Host learning without network config is required for CORD config generator.
1337 routingRulePopulator.populateIpPunts(device.id());
1338 routingRulePopulator.populateArpNdpPunts(device.id());
1339
Charles Chan0b4e6182015-11-03 10:42:14 -08001340 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001341 log.warn("Device configuration unavailable. Device {} will be "
1342 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001343 return;
1344 }
Charles Chan2199c302016-04-23 17:36:10 -07001345 processDeviceAddedInternal(device.id());
1346 }
1347
1348 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001349 // Irrespective of whether the local is a MASTER or not for this device,
1350 // we need to create a SR-group-handler instance. This is because in a
1351 // multi-instance setup, any instance can initiate forwarding/next-objectives
1352 // for any switch (even if this instance is a SLAVE or not even connected
1353 // to the switch). To handle this, a default-group-handler instance is necessary
1354 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001355 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1356 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001357 DefaultGroupHandler groupHandler;
1358 try {
1359 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001360 createGroupHandler(deviceId,
1361 appId,
1362 deviceConfiguration,
1363 linkService,
1364 flowObjectiveService,
1365 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001366 } catch (DeviceConfigNotFoundException e) {
1367 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1368 return;
1369 }
Saurav Das9aa28bd2017-12-05 15:00:23 -08001370 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001371 deviceId);
1372 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001373 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001374
Charles Chan2199c302016-04-23 17:36:10 -07001375 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001376 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001377 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001378 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001379 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001380 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001381 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001382 }
Charles Chan5270ed02016-01-30 23:22:37 -08001383
Charles Chan03a73e02016-10-24 14:52:01 -07001384 appCfgHandler.init(deviceId);
1385 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001386 }
1387
Saurav Das80980c72016-03-23 11:22:49 -07001388 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001389 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001390 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chanba90df12017-11-30 15:37:50 -08001391 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001392 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001393 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001394 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001395 portNextObjStore.entrySet().stream()
1396 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001397 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chaned3742352017-06-15 00:44:51 -07001398
1399 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1400 key.dst().deviceId().equals(device.id()));
1401
Saurav Dasceccf242017-08-03 18:30:35 -07001402 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1403 if (gh != null) {
1404 gh.shutdown();
1405 }
Saurav Das80980c72016-03-23 11:22:49 -07001406 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Dasc88d4662017-05-15 15:34:25 -07001407 // Note that a switch going down is associated with all of its links
1408 // going down as well, but it is treated as a single switch down event
1409 // while the link-downs are ignored.
1410 defaultRoutingHandler
1411 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan2199c302016-04-23 17:36:10 -07001412 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001413 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -07001414 }
1415
Saurav Das1a129a02016-11-18 15:21:57 -08001416 private void processPortUpdated(Device device, Port port) {
1417 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1418 log.warn("Device configuration uploading. Not handling port event for"
1419 + "dev: {} port: {}", device.id(), port.number());
1420 return;
1421 }
Saurav Das018605f2017-02-18 14:05:44 -08001422
1423 if (!mastershipService.isLocalMaster(device.id())) {
1424 log.debug("Not master for dev:{} .. not handling port updated event"
1425 + "for port {}", device.id(), port.number());
1426 return;
1427 }
1428
1429 // first we handle filtering rules associated with the port
1430 if (port.isEnabled()) {
1431 log.info("Switchport {}/{} enabled..programming filters",
1432 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001433 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001434 } else {
1435 log.info("Switchport {}/{} disabled..removing filters",
1436 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001437 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001438 }
Saurav Das1a129a02016-11-18 15:21:57 -08001439
1440 // portUpdated calls are for ports that have gone down or up. For switch
1441 // to switch ports, link-events should take care of any re-routing or
1442 // group editing necessary for port up/down. Here we only process edge ports
1443 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001444 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1445 VlanId untaggedVlan = getUntaggedVlanId(cp);
1446 VlanId nativeVlan = getNativeVlanId(cp);
1447 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001448
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001449 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001450 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001451 + "dev/port: {}/{}", device.id(), port.number());
1452 return;
1453 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001454 if (untaggedVlan != null) {
1455 processEdgePort(device, port, untaggedVlan, true);
1456 }
1457 if (nativeVlan != null) {
1458 processEdgePort(device, port, nativeVlan, true);
1459 }
1460 if (!taggedVlans.isEmpty()) {
1461 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1462 }
Saurav Das1a129a02016-11-18 15:21:57 -08001463 }
1464
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001465 private void processEdgePort(Device device, Port port, VlanId vlanId,
1466 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001467 boolean portUp = port.isEnabled();
1468 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001469 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001470 port.number(), vlanId);
Charles Chanba90df12017-11-30 15:37:50 -08001471 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001472 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001473 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001474 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001475 }
1476
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001477 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001478 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001479 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001480 } else {
1481 log.warn("Group handler not found for dev:{}. Not handling edge port"
1482 + " {} event for port:{}", device.id(),
1483 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001484 }
1485 }
sangho1e575652015-05-14 00:39:53 -07001486
Charles Chan463c6442017-10-20 16:06:55 -07001487 private void createOrUpdateDeviceConfiguration() {
1488 if (deviceConfiguration == null) {
1489 deviceConfiguration = new DeviceConfiguration(this);
1490 } else {
1491 deviceConfiguration.updateConfig();
1492 }
1493 }
1494
Pier Ventre10bd8d12016-11-26 21:05:22 -08001495 /**
1496 * Registers the given connect point with the NRS, this is necessary
1497 * to receive the NDP and ARP packets from the NRS.
1498 *
1499 * @param portToRegister connect point to register
1500 */
1501 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001502 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001503 portToRegister,
1504 neighbourHandler,
1505 appId
1506 );
1507 }
1508
Charles Chand6832882015-10-05 17:50:33 -07001509 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001510 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001511 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001512
Charles Chane849c192016-01-11 18:28:54 -08001513 /**
1514 * Constructs the internal network config listener.
1515 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001516 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001517 */
Charles Chan65238242017-06-22 18:03:14 -07001518 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001519 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001520 }
1521
Charles Chane849c192016-01-11 18:28:54 -08001522 /**
1523 * Reads network config and initializes related data structure accordingly.
1524 */
Charles Chanba90df12017-11-30 15:37:50 -08001525 void configureNetwork() {
Charles Chan463c6442017-10-20 16:06:55 -07001526 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001527
Charles Chan2c15aca2016-11-09 20:51:44 -08001528 arpHandler = new ArpHandler(srManager);
1529 icmpHandler = new IcmpHandler(srManager);
1530 ipHandler = new IpHandler(srManager);
1531 routingRulePopulator = new RoutingRulePopulator(srManager);
1532 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001533
1534 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1535 groupHandlerMap, tunnelStore);
1536 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1537 flowObjectiveService,
1538 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001539 // add a small delay to absorb multiple network config added notifications
1540 if (!programmingScheduled.get()) {
1541 programmingScheduled.set(true);
1542 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1543 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001544 }
Charles Chan2199c302016-04-23 17:36:10 -07001545 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001546 }
1547
Charles Chand6832882015-10-05 17:50:33 -07001548 @Override
1549 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001550 // TODO move this part to NetworkConfigEventHandler
1551 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1552 switch (event.type()) {
1553 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001554 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001555 configureNetwork();
1556 break;
1557 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001558 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001559 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001560 // TODO support dynamic configuration
1561 break;
1562 default:
1563 break;
1564 }
1565 } else if (event.configClass().equals(InterfaceConfig.class)) {
1566 switch (event.type()) {
1567 case CONFIG_ADDED:
1568 log.info("Interface Config added for {}", event.subject());
1569 configureNetwork();
1570 break;
1571 case CONFIG_UPDATED:
1572 log.info("Interface Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001573 createOrUpdateDeviceConfiguration();
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001574
1575 // Following code will be uncommented when [CORD-634] is fully implemented.
1576 // [CORD-634] Add dynamic config support for interfaces
1577 updateInterface((InterfaceConfig) event.config().get(),
1578 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001579 // TODO support dynamic configuration
1580 break;
1581 default:
1582 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001583 }
Charles Chan5270ed02016-01-30 23:22:37 -08001584 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001585 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001586 switch (event.type()) {
1587 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001588 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001589 break;
1590 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001591 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001592 break;
1593 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001594 appCfgHandler.processAppConfigRemoved(event);
1595 break;
1596 default:
1597 break;
1598 }
Charles Chan03a73e02016-10-24 14:52:01 -07001599 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001600 } else if (event.configClass().equals(XConnectConfig.class)) {
1601 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1602 switch (event.type()) {
1603 case CONFIG_ADDED:
1604 xConnectHandler.processXConnectConfigAdded(event);
1605 break;
1606 case CONFIG_UPDATED:
1607 xConnectHandler.processXConnectConfigUpdated(event);
1608 break;
1609 case CONFIG_REMOVED:
1610 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001611 break;
1612 default:
1613 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001614 }
Pier Ventref34966c2016-11-07 16:21:04 -08001615 } else if (event.configClass().equals(PwaasConfig.class)) {
1616 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1617 switch (event.type()) {
1618 case CONFIG_ADDED:
1619 l2TunnelHandler.processPwaasConfigAdded(event);
1620 break;
1621 case CONFIG_UPDATED:
1622 l2TunnelHandler.processPwaasConfigUpdated(event);
1623 break;
1624 case CONFIG_REMOVED:
1625 l2TunnelHandler.processPwaasConfigRemoved(event);
1626 break;
1627 default:
1628 break;
1629 }
Charles Chand6832882015-10-05 17:50:33 -07001630 }
1631 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001632
Charles Chan91b371b2018-01-03 16:26:32 -08001633 @Override
1634 public boolean isRelevant(NetworkConfigEvent event) {
1635 if (event.configClass().equals(SegmentRoutingDeviceConfig.class) ||
1636 event.configClass().equals(SegmentRoutingAppConfig.class) ||
1637 event.configClass().equals(InterfaceConfig.class) ||
1638 event.configClass().equals(XConnectConfig.class) ||
1639 event.configClass().equals(PwaasConfig.class)) {
1640 return true;
1641 }
1642 log.debug("Ignore irrelevant event class {}", event.configClass().getName());
1643 return false;
1644 }
1645
Saurav Das7bcbe702017-06-13 15:35:54 -07001646 private final class ConfigChange implements Runnable {
1647 @Override
1648 public void run() {
1649 programmingScheduled.set(false);
1650 for (Device device : deviceService.getDevices()) {
1651 processDeviceAdded(device);
1652 }
1653 defaultRoutingHandler.startPopulationProcess();
1654 }
1655 }
Charles Chand6832882015-10-05 17:50:33 -07001656 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001657
1658 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001659 @Override
1660 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001661 switch (event.type()) {
1662 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001663 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001664 break;
1665 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001666 hostHandler.processHostMovedEvent(event);
Charles Chan23686832017-08-23 14:46:43 -07001667 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001668 break;
1669 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001670 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001671 break;
1672 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001673 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001674 break;
1675 default:
1676 log.warn("Unsupported host event type: {}", event.type());
1677 break;
1678 }
1679 }
1680 }
1681
Charles Chand55e84d2016-03-30 17:54:24 -07001682 private class InternalMcastListener implements McastListener {
1683 @Override
1684 public void event(McastEvent event) {
1685 switch (event.type()) {
1686 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001687 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001688 break;
1689 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001690 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001691 break;
1692 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001693 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001694 break;
1695 case ROUTE_ADDED:
1696 case ROUTE_REMOVED:
1697 default:
1698 break;
1699 }
1700 }
1701 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001702
Charles Chan03a73e02016-10-24 14:52:01 -07001703 private class InternalRouteEventListener implements RouteListener {
1704 @Override
1705 public void event(RouteEvent event) {
1706 switch (event.type()) {
1707 case ROUTE_ADDED:
1708 routeHandler.processRouteAdded(event);
1709 break;
1710 case ROUTE_UPDATED:
1711 routeHandler.processRouteUpdated(event);
1712 break;
1713 case ROUTE_REMOVED:
1714 routeHandler.processRouteRemoved(event);
1715 break;
Charles Chan23686832017-08-23 14:46:43 -07001716 case ALTERNATIVE_ROUTES_CHANGED:
1717 routeHandler.processAlternativeRoutesChanged(event);
1718 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001719 default:
1720 break;
1721 }
1722 }
1723 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001724
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001725 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1726 try {
1727 Set<Interface> intfs = conf.getInterfaces();
1728 Set<Interface> prevIntfs = prevConf.getInterfaces();
1729
1730 // Now we only handle one interface config at each port.
1731 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1732 log.warn("Interface update aborted - one at a time is allowed, " +
1733 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1734 return;
1735 }
1736
1737 Interface intf = intfs.stream().findFirst().get();
1738 Interface prevIntf = prevIntfs.stream().findFirst().get();
1739
1740 DeviceId deviceId = intf.connectPoint().deviceId();
1741 PortNumber portNum = intf.connectPoint().port();
1742
1743 if (!mastershipService.isLocalMaster(deviceId)) {
1744 log.debug("CONFIG_UPDATED event for interfaces should be " +
1745 "handled by master node for device {}", deviceId);
1746 return;
1747 }
1748
1749 removeSubnetConfig(prevIntf.connectPoint(),
1750 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1751 new HashSet<>(intf.ipAddressesList())));
1752
1753 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1754 // RemoveVlanNative
1755 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1756 }
1757
1758 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1759 // RemoveVlanTagged
1760 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1761 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1762 );
1763 }
1764
1765 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1766 // RemoveVlanUntagged
1767 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1768 }
1769
1770 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1771 // AddVlanNative
1772 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1773 }
1774
1775 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1776 // AddVlanTagged
1777 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1778 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1779 );
1780 }
1781
1782 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1783 // AddVlanUntagged
1784 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1785 }
1786 addSubnetConfig(prevIntf.connectPoint(),
1787 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1788 new HashSet<>(prevIntf.ipAddressesList())));
1789 } catch (ConfigException e) {
1790 log.error("Error in configuration");
1791 }
1792 }
1793
1794 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1795 VlanId vlanId, boolean pushVlan, boolean install) {
1796 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1797 if (grpHandler == null) {
1798 log.warn("Failed to retrieve group handler for device {}", deviceId);
1799 return;
1800 }
1801
1802 // Update filtering objective for a single port
1803 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1804
1805 // Update filtering objective for multicast ingress port
1806 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1807
1808 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1809
1810 if (nextId != -1 && !install) {
1811 // Update next objective for a single port as an output port
1812 // Remove a single port from L2FG
1813 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1814 // Remove L2 Bridging rule and L3 Unicast rule to the host
1815 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1816 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1817 // only if there is no port configured on that VLAN ID
1818 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1819 // Remove broadcast forwarding rule for the VLAN
1820 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1821 // Remove L2FG for VLAN
1822 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1823 } else {
1824 // Remove L2IG of the port
1825 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1826 }
1827 } else if (install) {
1828 if (nextId != -1) {
1829 // Add a single port to L2FG
1830 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1831 } else {
1832 // Create L2FG for VLAN
1833 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1834 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1835 }
1836 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1837 } else {
1838 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1839 }
1840 }
1841
1842 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1843 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1844 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1845
1846 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1847 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1848 .filter(intf -> !intf.connectPoint().equals(cp))
1849 .flatMap(intf -> intf.ipAddressesList().stream())
1850 .collect(Collectors.toSet());
1851 // 1. Partial subnet population
1852 // Remove routing rules for removed subnet from previous configuration,
1853 // which does not also exist in other interfaces in the same device
1854 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1855 .map(InterfaceIpAddress::subnetAddress)
1856 .collect(Collectors.toSet());
1857
1858 defaultRoutingHandler.revokeSubnet(
1859 ipPrefixSet.stream()
1860 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1861 .collect(Collectors.toSet()));
1862
1863 // 2. Interface IP punts
1864 // Remove IP punts for old Intf address
1865 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1866 .map(InterfaceIpAddress::ipAddress)
1867 .collect(Collectors.toSet());
1868 ipAddressSet.stream()
1869 .map(InterfaceIpAddress::ipAddress)
1870 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1871 .forEach(interfaceIpAddress ->
1872 routingRulePopulator.revokeSingleIpPunts(
1873 cp.deviceId(), interfaceIpAddress));
1874
1875 // 3. Host unicast routing rule
1876 // Remove unicast routing rule
1877 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1878 }
1879
1880 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1881 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1882 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1883
1884 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1885 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1886 .filter(intf -> !intf.connectPoint().equals(cp))
1887 .flatMap(intf -> intf.ipAddressesList().stream())
1888 .collect(Collectors.toSet());
1889 // 1. Partial subnet population
1890 // Add routing rules for newly added subnet, which does not also exist in
1891 // other interfaces in the same device
1892 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1893 .map(InterfaceIpAddress::subnetAddress)
1894 .collect(Collectors.toSet());
1895
1896 defaultRoutingHandler.populateSubnet(
1897 Collections.singleton(cp),
1898 ipPrefixSet.stream()
1899 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1900 .collect(Collectors.toSet()));
1901
1902 // 2. Interface IP punts
1903 // Add IP punts for new Intf address
1904 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1905 .map(InterfaceIpAddress::ipAddress)
1906 .collect(Collectors.toSet());
1907 ipAddressSet.stream()
1908 .map(InterfaceIpAddress::ipAddress)
1909 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1910 .forEach(interfaceIpAddress ->
1911 routingRulePopulator.populateSingleIpPunts(
1912 cp.deviceId(), interfaceIpAddress));
1913
1914 // 3. Host unicast routing rule
1915 // Add unicast routing rule
1916 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1917 }
sanghob35a6192015-04-01 13:05:26 -07001918}