blob: cec93a78d93f167ffe5215f699241dcef7b16493 [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 Chan8d055212018-01-04 14:26:07 -0800426
427 cfgListener.configureNetwork();
428
Charles Chan5270ed02016-01-30 23:22:37 -0800429 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700430 packetService.addProcessor(processor, PacketProcessor.director(2));
431 linkService.addListener(linkListener);
432 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700433 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700434 routeService.addListener(routeListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700435
sanghob35a6192015-04-01 13:05:26 -0700436 log.info("Started");
437 }
438
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700439 private KryoNamespace.Builder createSerializer() {
440 return new KryoNamespace.Builder()
441 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700442 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan59cc16d2017-02-02 16:20:42 -0800443 VlanNextObjectiveStoreKey.class,
Saurav Das7bcbe702017-06-13 15:35:54 -0700444 DestinationSet.class,
445 NextNeighbors.class,
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700446 Tunnel.class,
447 DefaultTunnel.class,
448 Policy.class,
449 TunnelPolicy.class,
450 Policy.Type.class,
451 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700452 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700453 );
454 }
455
sanghob35a6192015-04-01 13:05:26 -0700456 @Deactivate
457 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700458 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700459 cfgService.unregisterConfigFactory(deviceConfigFactory);
460 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700461 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700462 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventref34966c2016-11-07 16:21:04 -0800463 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chanba90df12017-11-30 15:37:50 -0800464 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700465
Charles Chanc7a8a682017-06-19 00:43:31 -0700466 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700467 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700468 linkService.removeListener(linkListener);
469 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700470 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700471 routeService.removeListener(routeListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700472
Charles Chan0aa674e2017-02-23 15:44:08 -0800473 neighbourResolutionService.unregisterNeighbourHandlers(appId);
474
sanghob35a6192015-04-01 13:05:26 -0700475 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700476 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700477 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700478 groupHandlerMap.clear();
479
Saurav Das7bcbe702017-06-13 15:35:54 -0700480 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800481 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700482 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700483 tunnelStore.destroy();
484 policyStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700485 log.info("Stopped");
486 }
487
Charles Chanba90df12017-11-30 15:37:50 -0800488 @Modified
489 private void modified(ComponentContext context) {
490 Dictionary<?, ?> properties = context.getProperties();
491 if (properties == null) {
492 return;
493 }
494
495 String strActiveProving = Tools.get(properties, "activeProbing");
496 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
497
498 if (expectActiveProbing != activeProbing) {
499 activeProbing = expectActiveProbing;
500 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
501 }
502 }
503
sangho1e575652015-05-14 00:39:53 -0700504 @Override
505 public List<Tunnel> getTunnels() {
506 return tunnelHandler.getTunnels();
507 }
508
509 @Override
sangho71abe1b2015-06-29 14:58:47 -0700510 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
511 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700512 }
513
514 @Override
sangho71abe1b2015-06-29 14:58:47 -0700515 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700516 for (Policy policy: policyHandler.getPolicies()) {
517 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
518 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
519 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
520 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700521 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700522 }
523 }
524 }
sangho71abe1b2015-06-29 14:58:47 -0700525 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700526 }
527
528 @Override
sangho71abe1b2015-06-29 14:58:47 -0700529 public PolicyHandler.Result removePolicy(Policy policy) {
530 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700531 }
532
533 @Override
sangho71abe1b2015-06-29 14:58:47 -0700534 public PolicyHandler.Result createPolicy(Policy policy) {
535 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700536 }
537
538 @Override
539 public List<Policy> getPolicies() {
540 return policyHandler.getPolicies();
541 }
542
Saurav Das59232cf2016-04-27 18:35:50 -0700543 @Override
544 public void rerouteNetwork() {
545 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700546 }
547
Charles Chanc81c45b2016-10-20 17:02:44 -0700548 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800549 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
550 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chanc81c45b2016-10-20 17:02:44 -0700551 deviceService.getAvailableDevices().forEach(device -> {
552 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
553 });
554 return deviceSubnetMap;
555 }
556
Saurav Dasc88d4662017-05-15 15:34:25 -0700557
558 @Override
559 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
560 if (defaultRoutingHandler != null) {
561 return defaultRoutingHandler.getCurrentEmcpSpgMap();
562 } else {
563 return null;
564 }
565 }
566
567 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700568 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
569 if (dsNextObjStore != null) {
570 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700571 } else {
572 return ImmutableMap.of();
573 }
574 }
575
Saurav Dasceccf242017-08-03 18:30:35 -0700576 @Override
577 public void verifyGroups(DeviceId id) {
578 DefaultGroupHandler gh = groupHandlerMap.get(id);
579 if (gh != null) {
580 gh.triggerBucketCorrector();
581 }
582 }
583
sanghof9d0bf12015-05-19 11:57:42 -0700584 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700585 * Extracts the application ID from the manager.
586 *
587 * @return application ID
588 */
589 public ApplicationId appId() {
590 return appId;
591 }
592
593 /**
594 * Returns the device configuration.
595 *
596 * @return device configuration
597 */
598 public DeviceConfiguration deviceConfiguration() {
599 return deviceConfiguration;
600 }
601
602 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700603 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5deb3232017-08-22 15:07:34 -0700604 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700605 *
606 * @return next objective ID store
607 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700608 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
609 dsNextObjStore() {
610 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700611 }
612
613 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700614 * Per device next objective ID store with (device id + vlanid) as key.
615 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700616 *
617 * @return vlan next object store
618 */
619 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
620 return vlanNextObjStore;
621 }
622
623 /**
Charles Chan5deb3232017-08-22 15:07:34 -0700624 * Per device next objective ID store with (device id + port + treatment + meta) as key.
625 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700626 *
627 * @return port next object store.
628 */
629 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
630 return portNextObjStore;
631 }
632
633 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700634 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
635 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700636 *
637 * @return MPLS-ECMP value
638 */
639 public boolean getMplsEcmp() {
640 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
641 .getConfig(this.appId, SegmentRoutingAppConfig.class);
642 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
643 }
644
645 /**
sanghof9d0bf12015-05-19 11:57:42 -0700646 * Returns the tunnel object with the tunnel ID.
647 *
648 * @param tunnelId Tunnel ID
649 * @return Tunnel reference
650 */
sangho1e575652015-05-14 00:39:53 -0700651 public Tunnel getTunnel(String tunnelId) {
652 return tunnelHandler.getTunnel(tunnelId);
653 }
654
Charles Chan7ffd81f2017-02-08 15:52:08 -0800655 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700656 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800657 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800658 * <p>
659 * Only returns the first match if there are multiple untagged VLAN configured
660 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700661 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800662 * @param connectPoint connect point
663 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700664 */
Charles Chan65238242017-06-22 18:03:14 -0700665 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800666 return interfaceService.getInterfacesByPort(connectPoint).stream()
667 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
668 .map(Interface::vlanUntagged)
669 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700670 }
671
sangho1e575652015-05-14 00:39:53 -0700672 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800673 * Returns tagged VLAN configured on given connect point.
674 * <p>
675 * Returns all matches if there are multiple tagged VLAN configured
676 * on the connect point.
677 *
678 * @param connectPoint connect point
679 * @return tagged VLAN or empty set if not configured
680 */
Charles Chan65238242017-06-22 18:03:14 -0700681 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800682 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
683 return interfaces.stream()
684 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700685 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800686 .collect(Collectors.toSet());
687 }
688
689 /**
690 * Returns native VLAN configured on given connect point.
691 * <p>
692 * Only returns the first match if there are multiple native VLAN configured
693 * on the connect point.
694 *
695 * @param connectPoint connect point
696 * @return native VLAN or null if not configured
697 */
Charles Chan65238242017-06-22 18:03:14 -0700698 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800699 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
700 return interfaces.stream()
701 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
702 .map(Interface::vlanNative)
703 .findFirst()
704 .orElse(null);
705 }
706
707 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700708 * Returns internal VLAN for untagged hosts on given connect point.
709 * <p>
710 * The internal VLAN is either vlan-untagged for an access port,
711 * or vlan-native for a trunk port.
712 *
713 * @param connectPoint connect point
714 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
715 */
Charles Chan65238242017-06-22 18:03:14 -0700716 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700717 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
718 VlanId nativeVlanId = getNativeVlanId(connectPoint);
719 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
720 }
721
722 /**
Charles Chan65238242017-06-22 18:03:14 -0700723 * Returns optional pair device ID of given device.
724 *
725 * @param deviceId device ID
726 * @return optional pair device ID. Might be empty if pair device is not configured
727 */
728 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
729 SegmentRoutingDeviceConfig deviceConfig =
730 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
731 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
732 }
733 /**
734 * Returns optional pair device local port of given device.
735 *
736 * @param deviceId device ID
737 * @return optional pair device ID. Might be empty if pair device is not configured
738 */
739 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
740 SegmentRoutingDeviceConfig deviceConfig =
741 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
742 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
743 }
744
745 /**
Charles Chan23686832017-08-23 14:46:43 -0700746 * Determine if current instance is the master of given connect point.
747 *
748 * @param cp connect point
749 * @return true if current instance is the master of given connect point
750 */
751 boolean isMasterOf(ConnectPoint cp) {
752 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
753 if (!isMaster) {
754 log.debug(NOT_MASTER, cp);
755 }
756 return isMaster;
757 }
758
759 /**
Charles Chanb15d0102017-08-23 13:55:39 -0700760 * Returns locations of given resolved route.
761 *
762 * @param resolvedRoute resolved route
763 * @return locations of nexthop. Might be empty if next hop is not found
764 */
765 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
766 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
767 return Optional.ofNullable(hostService.getHost(hostId))
768 .map(Host::locations).orElse(Sets.newHashSet())
769 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
770 }
771
772 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800773 * Returns vlan port map of given device.
774 *
775 * @param deviceId device id
776 * @return vlan-port multimap
777 */
778 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
779 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
780
781 interfaceService.getInterfaces().stream()
782 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
783 .forEach(intf -> {
784 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700785 intf.vlanTagged().forEach(vlanTagged ->
786 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
787 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800788 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
789 });
790 vlanPortMap.removeAll(VlanId.NONE);
791
792 return vlanPortMap;
793 }
794
795 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800796 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800797 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700798 *
799 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800800 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800801 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700802 */
Charles Chan65238242017-06-22 18:03:14 -0700803 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700804 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800805 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
806 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700807 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800808 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800809 + "device {} not found", deviceId);
810 return -1;
811 }
812 }
813
814 /**
815 * Returns the next objective ID for the given portNumber, given the treatment.
816 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700817 * would result in different objectives. If the next object does not exist,
818 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800819 *
820 * @param deviceId Device ID
821 * @param portNum port number on device for which NextObjective is queried
822 * @param treatment the actions to apply on the packets (should include outport)
823 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700824 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700825 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800826 */
827 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
828 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700829 TrafficSelector meta,
830 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800831 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
832 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700833 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800834 } else {
Charles Chane849c192016-01-11 18:28:54 -0800835 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
836 + " not found", deviceId);
837 return -1;
838 }
839 }
840
Saurav Dasc88d4662017-05-15 15:34:25 -0700841 /**
842 * Returns the group handler object for the specified device id.
843 *
844 * @param devId the device identifier
845 * @return the groupHandler object for the device id, or null if not found
846 */
Charles Chan65238242017-06-22 18:03:14 -0700847 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700848 return groupHandlerMap.get(devId);
849 }
850
851 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700852 * Returns the default routing handler object.
853 *
854 * @return the default routing handler object
855 */
856 public DefaultRoutingHandler getRoutingHandler() {
857 return defaultRoutingHandler;
858 }
859
860 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700861 * Returns true if this controller instance has seen this link before. The
862 * link may not be currently up, but as long as the link had been seen before
863 * this method will return true. The one exception is when the link was
864 * indeed seen before, but this controller instance was forced to forget it
865 * by a call to purgeSeenLink method.
866 *
867 * @param link the infrastructure link being queried
868 * @return true if this controller instance has seen this link before
869 */
Charles Chan65238242017-06-22 18:03:14 -0700870 boolean isSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700871 return seenLinks.containsKey(link);
872 }
873
874 /**
875 * Updates the seen link store. Updates can be for links that are currently
876 * available or not.
877 *
878 * @param link the link to update in the seen-link local store
879 * @param up the status of the link, true if up, false if down
880 */
Charles Chan65238242017-06-22 18:03:14 -0700881 void updateSeenLink(Link link, boolean up) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700882 seenLinks.put(link, up);
883 }
884
885 /**
886 * Returns the status of a seen-link (up or down). If the link has not
887 * been seen-before, a null object is returned.
888 *
889 * @param link the infrastructure link being queried
890 * @return null if the link was not seen-before;
891 * true if the seen-link is up;
892 * false if the seen-link is down
893 */
Charles Chanba90df12017-11-30 15:37:50 -0800894 private Boolean isSeenLinkUp(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700895 return seenLinks.get(link);
896 }
897
898 /**
899 * Makes this controller instance forget a previously seen before link.
900 *
901 * @param link the infrastructure link to purge
902 */
Charles Chan65238242017-06-22 18:03:14 -0700903 private void purgeSeenLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700904 seenLinks.remove(link);
905 }
906
907 /**
908 * Returns the status of a link as parallel link. A parallel link
909 * is defined as a link which has common src and dst switches as another
910 * seen-link that is currently enabled. It is not necessary for the link being
911 * queried to be a seen-link.
912 *
913 * @param link the infrastructure link being queried
914 * @return true if a seen-link exists that is up, and shares the
915 * same src and dst switches as the link being queried
916 */
Charles Chan65238242017-06-22 18:03:14 -0700917 private boolean isParallelLink(Link link) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700918 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
919 Link seenLink = seen.getKey();
920 if (seenLink.equals(link)) {
921 continue;
922 }
923 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
924 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
925 seen.getValue()) {
926 return true;
927 }
928 }
929 return false;
930 }
931
Saurav Das7bcbe702017-06-13 15:35:54 -0700932 /**
933 * Returns true if the link being queried is a bidirectional link. A bidi
934 * link is defined as a link, whose reverse link - ie. the link in the reverse
935 * direction - has been seen-before and is up. It is not necessary for the link
936 * being queried to be a seen-link.
937 *
938 * @param link the infrastructure link being queried
939 * @return true if another unidirectional link exists in the reverse direction,
940 * has been seen-before and is up
941 */
Charles Chanba90df12017-11-30 15:37:50 -0800942 boolean isBidirectional(Link link) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700943 Link reverseLink = linkService.getLink(link.dst(), link.src());
944 if (reverseLink == null) {
945 return false;
946 }
947 Boolean result = isSeenLinkUp(reverseLink);
948 if (result == null) {
949 return false;
950 }
951 return result.booleanValue();
952 }
953
954 /**
955 * Determines if the given link should be avoided in routing calculations
956 * by policy or design.
957 *
958 * @param link the infrastructure link being queried
959 * @return true if link should be avoided
960 */
Charles Chanba90df12017-11-30 15:37:50 -0800961 boolean avoidLink(Link link) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700962 // XXX currently only avoids all pair-links. In the future can be
963 // extended to avoid any generic link
964 DeviceId src = link.src().deviceId();
965 PortNumber srcPort = link.src().port();
966 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
967 log.warn("Device {} not configured..cannot avoid link {}", src, link);
968 return false;
969 }
970 DeviceId pairDev;
971 PortNumber pairLocalPort, pairRemotePort = null;
972 try {
973 pairDev = deviceConfiguration.getPairDeviceId(src);
974 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
975 if (pairDev != null) {
976 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
977 }
978 } catch (DeviceConfigNotFoundException e) {
979 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
980 src, link);
981 return false;
982 }
983
Charles Chanba90df12017-11-30 15:37:50 -0800984 return srcPort.equals(pairLocalPort) &&
Saurav Das7bcbe702017-06-13 15:35:54 -0700985 link.dst().deviceId().equals(pairDev) &&
Charles Chanba90df12017-11-30 15:37:50 -0800986 link.dst().port().equals(pairRemotePort);
Saurav Das7bcbe702017-06-13 15:35:54 -0700987 }
988
sanghob35a6192015-04-01 13:05:26 -0700989 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700990 @Override
991 public void process(PacketContext context) {
992
993 if (context.isHandled()) {
994 return;
995 }
996
997 InboundPacket pkt = context.inPacket();
998 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -0800999
1000 if (ethernet == null) {
1001 return;
1002 }
1003
Saurav Das7bcbe702017-06-13 15:35:54 -07001004 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1005 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001006 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001007 log.warn("Received unexpected ARP packet on {}",
1008 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001009 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001010 return;
sanghob35a6192015-04-01 13:05:26 -07001011 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001012 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1013 //ipHandler.addToPacketBuffer(ipv4Packet);
1014 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1015 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001016 } else {
Charles Chan50035632017-01-13 17:20:44 -08001017 // NOTE: We don't support IP learning at this moment so this
1018 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001019 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001020 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001021 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1022 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001023 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001024 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001025 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1026 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1027 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1028 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1029 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1030 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001031 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001032 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001033 }
1034 } else {
1035 // NOTE: We don't support IP learning at this moment so this
1036 // is not necessary. Also it causes duplication of DHCPv6 packets.
1037 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1038 }
sanghob35a6192015-04-01 13:05:26 -07001039 }
1040 }
1041 }
1042
1043 private class InternalLinkListener implements LinkListener {
1044 @Override
1045 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001046 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1047 event.type() == LinkEvent.Type.LINK_UPDATED ||
1048 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001049 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001050 scheduleEventHandlerIfNotScheduled(event);
1051 }
1052 }
1053 }
1054
1055 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001056 @Override
1057 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001058 switch (event.type()) {
1059 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001060 case PORT_UPDATED:
1061 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001062 case DEVICE_UPDATED:
1063 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001064 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001065 scheduleEventHandlerIfNotScheduled(event);
1066 break;
1067 default:
1068 }
1069 }
1070 }
1071
Saurav Das4ce45962015-11-24 23:21:05 -08001072 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001073 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001074 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001075 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001076 numOfEventsQueued++;
1077
1078 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1079 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001080 eventHandlerFuture = executorService
1081 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1082 numOfHandlerScheduled++;
1083 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001084 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001085 numOfEventsQueued,
1086 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001087 }
sanghob35a6192015-04-01 13:05:26 -07001088 }
1089
1090 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001091 @Override
sanghob35a6192015-04-01 13:05:26 -07001092 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001093 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001094 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -08001095 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001096 Event event;
1097 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001098 if (!eventQueue.isEmpty()) {
1099 event = eventQueue.poll();
1100 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001101 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001102 numOfHandlerExecution++;
1103 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1104 numOfHandlerExecution, numOfEventsExecuted);
1105 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001106 }
sangho20eff1d2015-04-13 15:15:58 -07001107 }
Charles Chanb1f8c762017-03-29 16:39:05 -07001108 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1109 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001110 // Note: do not update seenLinks here, otherwise every
1111 // link, even one seen for the first time, will be appear
1112 // to be a previously seen link
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001113 processLinkAdded((Link) event.subject());
1114 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -07001115 Link linkRemoved = (Link) event.subject();
Saurav Dasc88d4662017-05-15 15:34:25 -07001116 if (linkRemoved.type() == Link.Type.DIRECT) {
1117 updateSeenLink(linkRemoved, false);
1118 }
1119 // device availability check helps to ensure that
1120 // multiple link-removed events are actually treated as a
1121 // single switch removed event. purgeSeenLink is necessary
1122 // so we do rerouting (instead of rehashing) when switch
1123 // comes back.
Pier Ventre2c515312016-09-13 21:33:40 -07001124 if (linkRemoved.src().elementId() instanceof DeviceId &&
1125 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001126 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001127 continue;
1128 }
1129 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1130 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001131 purgeSeenLink(linkRemoved);
Pier Ventre2c515312016-09-13 21:33:40 -07001132 continue;
1133 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001134 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001135 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1136 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1137 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001138 DeviceId deviceId = ((Device) event.subject()).id();
1139 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001140 log.info("Processing device event {} for available device {}",
1141 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001142 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001143 } else {
1144 log.info("Processing device event {} for unavailable device {}",
1145 event.type(), ((Device) event.subject()).id());
1146 processDeviceRemoved((Device) event.subject());
1147 }
Saurav Das1a129a02016-11-18 15:21:57 -08001148 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001149 // typically these calls come when device is added first time
1150 // so port filtering rules are handled at the device_added event.
1151 // port added calls represent all ports on the device,
1152 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001153 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001154 ((DeviceEvent) event).subject().id(),
1155 ((DeviceEvent) event).port().number(),
1156 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001157 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001158 // these calls happen for every subsequent event
1159 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001160 log.info("** PORT UPDATED {}/{} -> {}",
1161 event.subject(),
1162 ((DeviceEvent) event).port(),
1163 event.type());
1164 processPortUpdated(((Device) event.subject()),
1165 ((DeviceEvent) event).port());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001166 } else {
1167 log.warn("Unhandled event type: {}", event.type());
1168 }
sanghob35a6192015-04-01 13:05:26 -07001169 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001170 } catch (Exception e) {
1171 log.error("SegmentRouting event handler "
1172 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -07001173 }
sanghob35a6192015-04-01 13:05:26 -07001174 }
1175 }
1176
sanghob35a6192015-04-01 13:05:26 -07001177 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001178 log.info("** LINK ADDED {}", link.toString());
Saurav Das92f01e12017-12-19 16:08:42 -08001179 if (!isLinkValid(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001180 return;
1181 }
Saurav Das041bb782017-08-14 16:44:43 -07001182 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1183 updateSeenLink(link, true);
1184 // XXX revisit - what about devicePortMap
1185 log.warn("Source device of this link is not configured.. "
1186 + "not processing further");
1187 return;
1188 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001189
1190 //Irrespective of whether the local is a MASTER or not for this device,
1191 //create group handler instance and push default TTP flow rules if needed,
1192 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001193 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1194 .deviceId());
1195 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001196 groupHandler.portUpForLink(link);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001197 } else {
Saurav Das041bb782017-08-14 16:44:43 -07001198 // XXX revisit/cleanup
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001199 Device device = deviceService.getDevice(link.src().deviceId());
1200 if (device != null) {
1201 log.warn("processLinkAdded: Link Added "
1202 + "Notification without Device Added "
1203 + "event, still handling it");
1204 processDeviceAdded(device);
1205 groupHandler = groupHandlerMap.get(link.src()
1206 .deviceId());
Saurav Dasc88d4662017-05-15 15:34:25 -07001207 groupHandler.portUpForLink(link);
sanghob35a6192015-04-01 13:05:26 -07001208 }
1209 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001210
Saurav Das7bcbe702017-06-13 15:35:54 -07001211 /*// process link only if it is bidirectional
1212 if (!isBidirectional(link)) {
1213 log.debug("Link not bidirectional.. waiting for other direction "
1214 + "src {} --> dst {} ", link.dst(), link.src());
1215 // note that if we are not processing for routing, it should at least
1216 // be considered a seen-link
1217 updateSeenLink(link, true);
1218 return;
1219 }
1220 TO DO this ensure that rehash is still done correctly even if link is
1221 not processed for rerouting - perhaps rehash in both directions when
1222 it ultimately becomes bidi?
1223 */
1224
1225 log.debug("Starting optimized route population process for link "
1226 + "{} --> {}", link.src(), link.dst());
Saurav Dasc88d4662017-05-15 15:34:25 -07001227 boolean seenBefore = isSeenLink(link);
1228 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das7bcbe702017-06-13 15:35:54 -07001229
1230 // It's possible that linkUp causes no route-path change as ECMP graph does
1231 // not change if the link is a parallel link (same src-dst as another link.
1232 // However we still need to update ECMP hash groups to include new buckets
1233 // for the link that has come up.
Saurav Dasc88d4662017-05-15 15:34:25 -07001234 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001235 if (!seenBefore && isParallelLink(link)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001236 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das7bcbe702017-06-13 15:35:54 -07001237 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001238 groupHandler.retryHash(link, false, true);
1239 } else {
1240 //seen before-link
1241 if (isParallelLink(link)) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001242 log.debug("Attempting retryHash for paralled seen-before "
1243 + "link {}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001244 groupHandler.retryHash(link, false, false);
1245 }
1246 }
1247 }
Charles Chan2199c302016-04-23 17:36:10 -07001248
1249 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -07001250 }
1251
1252 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001253 log.info("** LINK REMOVED {}", link.toString());
Saurav Das92f01e12017-12-19 16:08:42 -08001254 if (!isLinkValid(link)) {
1255 return;
1256 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001257 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1258
1259 // update local groupHandler stores
sangho834e4b02015-05-01 09:38:25 -07001260 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1261 if (groupHandler != null) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001262 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1263 isParallelLink(link)) {
Saurav Das041bb782017-08-14 16:44:43 -07001264 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Dasc88d4662017-05-15 15:34:25 -07001265 groupHandler.retryHash(link, true, false);
Saurav Das041bb782017-08-14 16:44:43 -07001266 } else {
1267 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1268 (mastershipService.isLocalMaster(link.src().deviceId()))
1269 ? "not parallel" : "not master");
Saurav Dasc88d4662017-05-15 15:34:25 -07001270 }
1271 // ensure local stores are updated
1272 groupHandler.portDown(link.src().port());
1273 } else {
1274 log.warn("group handler not found for dev:{} when removing link: {}",
1275 link.src().deviceId(), link);
sangho834e4b02015-05-01 09:38:25 -07001276 }
Charles Chan2199c302016-04-23 17:36:10 -07001277
1278 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -07001279 }
1280
Saurav Das92f01e12017-12-19 16:08:42 -08001281 private boolean isLinkValid(Link link) {
1282 if (link.type() != Link.Type.DIRECT) {
1283 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1284 // if BDDP is received before LLDP. We can safely ignore that
1285 // until the LLDP is received and the link is marked as DIRECT.
1286 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1287 link.src(), link.dst(), link.type());
1288 return false;
1289 }
1290 DeviceId srcId = link.src().deviceId();
1291 DeviceId dstId = link.dst().deviceId();
1292 if (srcId.equals(dstId)) {
1293 log.warn("Links between ports on the same switch are not "
1294 + "allowed .. ignoring link {}", link);
1295 return false;
1296 }
1297 try {
1298 if (!deviceConfiguration.isEdgeDevice(srcId)
1299 && !deviceConfiguration.isEdgeDevice(dstId)) {
1300 // ignore links between spines
1301 // XXX revisit when handling multi-stage fabrics
1302 log.warn("Links between spines not allowed...ignoring "
1303 + "link {}", link);
1304 return false;
1305 }
1306 if (deviceConfiguration.isEdgeDevice(srcId)
1307 && deviceConfiguration.isEdgeDevice(dstId)) {
1308 // ignore links between leaves if they are not pair-links
1309 // XXX revisit if removing pair-link config or allowing more than
1310 // one pair-link
1311 if (deviceConfiguration.getPairDeviceId(srcId).equals(dstId)
1312 && deviceConfiguration.getPairLocalPort(srcId)
1313 .equals(link.src().port())
1314 && deviceConfiguration.getPairLocalPort(dstId)
1315 .equals(link.dst().port())) {
1316 // found pair link - allow it
1317 return true;
1318 } else {
1319 log.warn("Links between leaves other than pair-links are "
1320 + "not allowed...ignoring link {}", link);
1321 return false;
1322 }
1323 }
1324 } catch (DeviceConfigNotFoundException e) {
1325 // We still want to count the links in seenLinks even though there
1326 // is no config. So we let it return true
1327 log.warn("Could not check validity of link {} as subtending devices "
1328 + "are not yet configured", link);
1329 }
1330 return true;
1331 }
1332
sanghob35a6192015-04-01 13:05:26 -07001333 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001334 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001335
1336 // NOTE: Punt ARP/NDP even when the device is not configured.
1337 // Host learning without network config is required for CORD config generator.
1338 routingRulePopulator.populateIpPunts(device.id());
1339 routingRulePopulator.populateArpNdpPunts(device.id());
1340
Charles Chan0b4e6182015-11-03 10:42:14 -08001341 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001342 log.warn("Device configuration unavailable. Device {} will be "
1343 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001344 return;
1345 }
Charles Chan2199c302016-04-23 17:36:10 -07001346 processDeviceAddedInternal(device.id());
1347 }
1348
1349 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001350 // Irrespective of whether the local is a MASTER or not for this device,
1351 // we need to create a SR-group-handler instance. This is because in a
1352 // multi-instance setup, any instance can initiate forwarding/next-objectives
1353 // for any switch (even if this instance is a SLAVE or not even connected
1354 // to the switch). To handle this, a default-group-handler instance is necessary
1355 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001356 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1357 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001358 DefaultGroupHandler groupHandler;
1359 try {
1360 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001361 createGroupHandler(deviceId,
1362 appId,
1363 deviceConfiguration,
1364 linkService,
1365 flowObjectiveService,
1366 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001367 } catch (DeviceConfigNotFoundException e) {
1368 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1369 return;
1370 }
Saurav Das9aa28bd2017-12-05 15:00:23 -08001371 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001372 deviceId);
1373 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001374 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001375
Charles Chan2199c302016-04-23 17:36:10 -07001376 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001377 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001378 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001379 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001380 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001381 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001382 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001383 }
Charles Chan5270ed02016-01-30 23:22:37 -08001384
Charles Chan03a73e02016-10-24 14:52:01 -07001385 appCfgHandler.init(deviceId);
1386 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001387 }
1388
Saurav Das80980c72016-03-23 11:22:49 -07001389 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001390 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001391 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chanba90df12017-11-30 15:37:50 -08001392 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001393 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001394 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001395 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001396 portNextObjStore.entrySet().stream()
1397 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001398 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chaned3742352017-06-15 00:44:51 -07001399
1400 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1401 key.dst().deviceId().equals(device.id()));
1402
Saurav Dasceccf242017-08-03 18:30:35 -07001403 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1404 if (gh != null) {
1405 gh.shutdown();
1406 }
Saurav Das80980c72016-03-23 11:22:49 -07001407 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Dasc88d4662017-05-15 15:34:25 -07001408 // Note that a switch going down is associated with all of its links
1409 // going down as well, but it is treated as a single switch down event
1410 // while the link-downs are ignored.
1411 defaultRoutingHandler
1412 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan2199c302016-04-23 17:36:10 -07001413 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001414 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -07001415 }
1416
Saurav Das1a129a02016-11-18 15:21:57 -08001417 private void processPortUpdated(Device device, Port port) {
1418 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1419 log.warn("Device configuration uploading. Not handling port event for"
1420 + "dev: {} port: {}", device.id(), port.number());
1421 return;
1422 }
Saurav Das018605f2017-02-18 14:05:44 -08001423
1424 if (!mastershipService.isLocalMaster(device.id())) {
1425 log.debug("Not master for dev:{} .. not handling port updated event"
1426 + "for port {}", device.id(), port.number());
1427 return;
1428 }
1429
1430 // first we handle filtering rules associated with the port
1431 if (port.isEnabled()) {
1432 log.info("Switchport {}/{} enabled..programming filters",
1433 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001434 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001435 } else {
1436 log.info("Switchport {}/{} disabled..removing filters",
1437 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001438 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001439 }
Saurav Das1a129a02016-11-18 15:21:57 -08001440
1441 // portUpdated calls are for ports that have gone down or up. For switch
1442 // to switch ports, link-events should take care of any re-routing or
1443 // group editing necessary for port up/down. Here we only process edge ports
1444 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001445 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1446 VlanId untaggedVlan = getUntaggedVlanId(cp);
1447 VlanId nativeVlan = getNativeVlanId(cp);
1448 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001449
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001450 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001451 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001452 + "dev/port: {}/{}", device.id(), port.number());
1453 return;
1454 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001455 if (untaggedVlan != null) {
1456 processEdgePort(device, port, untaggedVlan, true);
1457 }
1458 if (nativeVlan != null) {
1459 processEdgePort(device, port, nativeVlan, true);
1460 }
1461 if (!taggedVlans.isEmpty()) {
1462 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1463 }
Saurav Das1a129a02016-11-18 15:21:57 -08001464 }
1465
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001466 private void processEdgePort(Device device, Port port, VlanId vlanId,
1467 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001468 boolean portUp = port.isEnabled();
1469 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001470 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001471 port.number(), vlanId);
Charles Chanba90df12017-11-30 15:37:50 -08001472 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001473 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001474 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001475 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001476 }
1477
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001478 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001479 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001480 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001481 } else {
1482 log.warn("Group handler not found for dev:{}. Not handling edge port"
1483 + " {} event for port:{}", device.id(),
1484 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001485 }
1486 }
sangho1e575652015-05-14 00:39:53 -07001487
Charles Chan463c6442017-10-20 16:06:55 -07001488 private void createOrUpdateDeviceConfiguration() {
1489 if (deviceConfiguration == null) {
1490 deviceConfiguration = new DeviceConfiguration(this);
1491 } else {
1492 deviceConfiguration.updateConfig();
1493 }
1494 }
1495
Pier Ventre10bd8d12016-11-26 21:05:22 -08001496 /**
1497 * Registers the given connect point with the NRS, this is necessary
1498 * to receive the NDP and ARP packets from the NRS.
1499 *
1500 * @param portToRegister connect point to register
1501 */
1502 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001503 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001504 portToRegister,
1505 neighbourHandler,
1506 appId
1507 );
1508 }
1509
Charles Chand6832882015-10-05 17:50:33 -07001510 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001511 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001512 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001513
Charles Chane849c192016-01-11 18:28:54 -08001514 /**
1515 * Constructs the internal network config listener.
1516 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001517 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001518 */
Charles Chan65238242017-06-22 18:03:14 -07001519 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001520 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001521 }
1522
Charles Chane849c192016-01-11 18:28:54 -08001523 /**
1524 * Reads network config and initializes related data structure accordingly.
1525 */
Charles Chanba90df12017-11-30 15:37:50 -08001526 void configureNetwork() {
Charles Chan463c6442017-10-20 16:06:55 -07001527 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001528
Charles Chan2c15aca2016-11-09 20:51:44 -08001529 arpHandler = new ArpHandler(srManager);
1530 icmpHandler = new IcmpHandler(srManager);
1531 ipHandler = new IpHandler(srManager);
1532 routingRulePopulator = new RoutingRulePopulator(srManager);
1533 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001534
1535 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1536 groupHandlerMap, tunnelStore);
1537 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1538 flowObjectiveService,
1539 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001540 // add a small delay to absorb multiple network config added notifications
1541 if (!programmingScheduled.get()) {
1542 programmingScheduled.set(true);
1543 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1544 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001545 }
Charles Chan2199c302016-04-23 17:36:10 -07001546 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001547 }
1548
Charles Chand6832882015-10-05 17:50:33 -07001549 @Override
1550 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001551 // TODO move this part to NetworkConfigEventHandler
1552 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1553 switch (event.type()) {
1554 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001555 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001556 configureNetwork();
1557 break;
1558 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001559 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001560 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001561 // TODO support dynamic configuration
1562 break;
1563 default:
1564 break;
1565 }
1566 } else if (event.configClass().equals(InterfaceConfig.class)) {
1567 switch (event.type()) {
1568 case CONFIG_ADDED:
1569 log.info("Interface Config added for {}", event.subject());
1570 configureNetwork();
1571 break;
1572 case CONFIG_UPDATED:
1573 log.info("Interface Config updated for {}", event.subject());
Charles Chan463c6442017-10-20 16:06:55 -07001574 createOrUpdateDeviceConfiguration();
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001575
1576 // Following code will be uncommented when [CORD-634] is fully implemented.
1577 // [CORD-634] Add dynamic config support for interfaces
1578 updateInterface((InterfaceConfig) event.config().get(),
1579 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001580 // TODO support dynamic configuration
1581 break;
1582 default:
1583 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001584 }
Charles Chan5270ed02016-01-30 23:22:37 -08001585 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001586 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001587 switch (event.type()) {
1588 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001589 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001590 break;
1591 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001592 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001593 break;
1594 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001595 appCfgHandler.processAppConfigRemoved(event);
1596 break;
1597 default:
1598 break;
1599 }
Charles Chan03a73e02016-10-24 14:52:01 -07001600 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001601 } else if (event.configClass().equals(XConnectConfig.class)) {
1602 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1603 switch (event.type()) {
1604 case CONFIG_ADDED:
1605 xConnectHandler.processXConnectConfigAdded(event);
1606 break;
1607 case CONFIG_UPDATED:
1608 xConnectHandler.processXConnectConfigUpdated(event);
1609 break;
1610 case CONFIG_REMOVED:
1611 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001612 break;
1613 default:
1614 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001615 }
Pier Ventref34966c2016-11-07 16:21:04 -08001616 } else if (event.configClass().equals(PwaasConfig.class)) {
1617 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1618 switch (event.type()) {
1619 case CONFIG_ADDED:
1620 l2TunnelHandler.processPwaasConfigAdded(event);
1621 break;
1622 case CONFIG_UPDATED:
1623 l2TunnelHandler.processPwaasConfigUpdated(event);
1624 break;
1625 case CONFIG_REMOVED:
1626 l2TunnelHandler.processPwaasConfigRemoved(event);
1627 break;
1628 default:
1629 break;
1630 }
Charles Chand6832882015-10-05 17:50:33 -07001631 }
1632 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001633
Charles Chan91b371b2018-01-03 16:26:32 -08001634 @Override
1635 public boolean isRelevant(NetworkConfigEvent event) {
1636 if (event.configClass().equals(SegmentRoutingDeviceConfig.class) ||
1637 event.configClass().equals(SegmentRoutingAppConfig.class) ||
1638 event.configClass().equals(InterfaceConfig.class) ||
1639 event.configClass().equals(XConnectConfig.class) ||
1640 event.configClass().equals(PwaasConfig.class)) {
1641 return true;
1642 }
1643 log.debug("Ignore irrelevant event class {}", event.configClass().getName());
1644 return false;
1645 }
1646
Saurav Das7bcbe702017-06-13 15:35:54 -07001647 private final class ConfigChange implements Runnable {
1648 @Override
1649 public void run() {
1650 programmingScheduled.set(false);
1651 for (Device device : deviceService.getDevices()) {
1652 processDeviceAdded(device);
1653 }
1654 defaultRoutingHandler.startPopulationProcess();
1655 }
1656 }
Charles Chand6832882015-10-05 17:50:33 -07001657 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001658
1659 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001660 @Override
1661 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001662 switch (event.type()) {
1663 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001664 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001665 break;
1666 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001667 hostHandler.processHostMovedEvent(event);
Charles Chan23686832017-08-23 14:46:43 -07001668 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001669 break;
1670 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001671 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001672 break;
1673 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001674 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001675 break;
1676 default:
1677 log.warn("Unsupported host event type: {}", event.type());
1678 break;
1679 }
1680 }
1681 }
1682
Charles Chand55e84d2016-03-30 17:54:24 -07001683 private class InternalMcastListener implements McastListener {
1684 @Override
1685 public void event(McastEvent event) {
1686 switch (event.type()) {
1687 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001688 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001689 break;
1690 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001691 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001692 break;
1693 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001694 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001695 break;
1696 case ROUTE_ADDED:
1697 case ROUTE_REMOVED:
1698 default:
1699 break;
1700 }
1701 }
1702 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001703
Charles Chan03a73e02016-10-24 14:52:01 -07001704 private class InternalRouteEventListener implements RouteListener {
1705 @Override
1706 public void event(RouteEvent event) {
1707 switch (event.type()) {
1708 case ROUTE_ADDED:
1709 routeHandler.processRouteAdded(event);
1710 break;
1711 case ROUTE_UPDATED:
1712 routeHandler.processRouteUpdated(event);
1713 break;
1714 case ROUTE_REMOVED:
1715 routeHandler.processRouteRemoved(event);
1716 break;
Charles Chan23686832017-08-23 14:46:43 -07001717 case ALTERNATIVE_ROUTES_CHANGED:
1718 routeHandler.processAlternativeRoutesChanged(event);
1719 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001720 default:
1721 break;
1722 }
1723 }
1724 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001725
Jonghwan Hyun5f1def82017-08-25 17:48:36 -07001726 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1727 try {
1728 Set<Interface> intfs = conf.getInterfaces();
1729 Set<Interface> prevIntfs = prevConf.getInterfaces();
1730
1731 // Now we only handle one interface config at each port.
1732 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1733 log.warn("Interface update aborted - one at a time is allowed, " +
1734 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1735 return;
1736 }
1737
1738 Interface intf = intfs.stream().findFirst().get();
1739 Interface prevIntf = prevIntfs.stream().findFirst().get();
1740
1741 DeviceId deviceId = intf.connectPoint().deviceId();
1742 PortNumber portNum = intf.connectPoint().port();
1743
1744 if (!mastershipService.isLocalMaster(deviceId)) {
1745 log.debug("CONFIG_UPDATED event for interfaces should be " +
1746 "handled by master node for device {}", deviceId);
1747 return;
1748 }
1749
1750 removeSubnetConfig(prevIntf.connectPoint(),
1751 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1752 new HashSet<>(intf.ipAddressesList())));
1753
1754 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1755 // RemoveVlanNative
1756 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1757 }
1758
1759 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1760 // RemoveVlanTagged
1761 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1762 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1763 );
1764 }
1765
1766 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1767 // RemoveVlanUntagged
1768 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1769 }
1770
1771 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1772 // AddVlanNative
1773 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1774 }
1775
1776 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1777 // AddVlanTagged
1778 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1779 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1780 );
1781 }
1782
1783 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1784 // AddVlanUntagged
1785 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1786 }
1787 addSubnetConfig(prevIntf.connectPoint(),
1788 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1789 new HashSet<>(prevIntf.ipAddressesList())));
1790 } catch (ConfigException e) {
1791 log.error("Error in configuration");
1792 }
1793 }
1794
1795 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1796 VlanId vlanId, boolean pushVlan, boolean install) {
1797 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1798 if (grpHandler == null) {
1799 log.warn("Failed to retrieve group handler for device {}", deviceId);
1800 return;
1801 }
1802
1803 // Update filtering objective for a single port
1804 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1805
1806 // Update filtering objective for multicast ingress port
1807 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1808
1809 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1810
1811 if (nextId != -1 && !install) {
1812 // Update next objective for a single port as an output port
1813 // Remove a single port from L2FG
1814 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1815 // Remove L2 Bridging rule and L3 Unicast rule to the host
1816 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1817 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1818 // only if there is no port configured on that VLAN ID
1819 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1820 // Remove broadcast forwarding rule for the VLAN
1821 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1822 // Remove L2FG for VLAN
1823 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1824 } else {
1825 // Remove L2IG of the port
1826 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1827 }
1828 } else if (install) {
1829 if (nextId != -1) {
1830 // Add a single port to L2FG
1831 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1832 } else {
1833 // Create L2FG for VLAN
1834 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1835 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1836 }
1837 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1838 } else {
1839 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1840 }
1841 }
1842
1843 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1844 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1845 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1846
1847 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1848 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1849 .filter(intf -> !intf.connectPoint().equals(cp))
1850 .flatMap(intf -> intf.ipAddressesList().stream())
1851 .collect(Collectors.toSet());
1852 // 1. Partial subnet population
1853 // Remove routing rules for removed subnet from previous configuration,
1854 // which does not also exist in other interfaces in the same device
1855 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1856 .map(InterfaceIpAddress::subnetAddress)
1857 .collect(Collectors.toSet());
1858
1859 defaultRoutingHandler.revokeSubnet(
1860 ipPrefixSet.stream()
1861 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1862 .collect(Collectors.toSet()));
1863
1864 // 2. Interface IP punts
1865 // Remove IP punts for old Intf address
1866 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1867 .map(InterfaceIpAddress::ipAddress)
1868 .collect(Collectors.toSet());
1869 ipAddressSet.stream()
1870 .map(InterfaceIpAddress::ipAddress)
1871 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1872 .forEach(interfaceIpAddress ->
1873 routingRulePopulator.revokeSingleIpPunts(
1874 cp.deviceId(), interfaceIpAddress));
1875
1876 // 3. Host unicast routing rule
1877 // Remove unicast routing rule
1878 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1879 }
1880
1881 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1882 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1883 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1884
1885 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1886 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1887 .filter(intf -> !intf.connectPoint().equals(cp))
1888 .flatMap(intf -> intf.ipAddressesList().stream())
1889 .collect(Collectors.toSet());
1890 // 1. Partial subnet population
1891 // Add routing rules for newly added subnet, which does not also exist in
1892 // other interfaces in the same device
1893 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1894 .map(InterfaceIpAddress::subnetAddress)
1895 .collect(Collectors.toSet());
1896
1897 defaultRoutingHandler.populateSubnet(
1898 Collections.singleton(cp),
1899 ipPrefixSet.stream()
1900 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1901 .collect(Collectors.toSet()));
1902
1903 // 2. Interface IP punts
1904 // Add IP punts for new Intf address
1905 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1906 .map(InterfaceIpAddress::ipAddress)
1907 .collect(Collectors.toSet());
1908 ipAddressSet.stream()
1909 .map(InterfaceIpAddress::ipAddress)
1910 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1911 .forEach(interfaceIpAddress ->
1912 routingRulePopulator.populateSingleIpPunts(
1913 cp.deviceId(), interfaceIpAddress));
1914
1915 // 3. Host unicast routing rule
1916 // Add unicast routing rule
1917 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1918 }
sanghob35a6192015-04-01 13:05:26 -07001919}