blob: fe01fd3b4aa97f310377e84f4e8f6a5ad2b6f2c4 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart61e24e12017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chanf0ae41e2017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
Charles Chan873661e2017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sangho80f11cb2015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Pier Luigi580fd8a2018-01-16 10:47:50 +010041import org.onosproject.cluster.ClusterService;
42import org.onosproject.cluster.LeadershipService;
sangho80f11cb2015-04-01 13:05:26 -070043import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.event.Event;
Jonathan Hart54541d12016-04-12 15:39:44 -070046import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070047import org.onosproject.mcast.api.McastEvent;
48import org.onosproject.mcast.api.McastListener;
49import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080050import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070051import org.onosproject.net.Device;
52import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070053import org.onosproject.net.Host;
54import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070055import org.onosproject.net.Link;
56import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080057import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070058import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070059import org.onosproject.net.config.ConfigFactory;
60import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070061import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070062import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070063import org.onosproject.net.config.basics.InterfaceConfig;
64import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070065import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080066import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070067import org.onosproject.net.device.DeviceEvent;
68import org.onosproject.net.device.DeviceListener;
69import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080070import org.onosproject.net.flow.TrafficSelector;
71import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070072import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080073import org.onosproject.net.host.HostEvent;
74import org.onosproject.net.host.HostListener;
Charles Chan873661e2017-11-30 15:37:50 -080075import org.onosproject.net.host.HostLocationProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080076import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070077import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyae0068a2017-08-15 11:02:29 -070078import org.onosproject.net.intf.Interface;
79import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080080import org.onosproject.net.link.LinkEvent;
81import org.onosproject.net.link.LinkListener;
82import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
96import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -080097import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -070098import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -070099import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700101import org.onosproject.segmentrouting.grouphandler.DestinationSet;
102import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi69f774d2018-02-28 12:10:50 +0100103import org.onosproject.segmentrouting.mcast.McastHandler;
104import org.onosproject.segmentrouting.mcast.McastRole;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700105import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700106import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800109
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800112import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
114
Saurav Das261c3002017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigi0f9635b2018-01-15 18:06:43 +0100116import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hart54541d12016-04-12 15:39:44 -0700120import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700121import org.onosproject.store.service.EventuallyConsistentMap;
122import org.onosproject.store.service.EventuallyConsistentMapBuilder;
123import org.onosproject.store.service.StorageService;
124import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800125import org.osgi.service.component.ComponentContext;
sangho80f11cb2015-04-01 13:05:26 -0700126import org.slf4j.Logger;
127import org.slf4j.LoggerFactory;
128
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700129import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800130import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800131import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800132import java.util.HashSet;
133import java.util.List;
134import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800135import java.util.Optional;
136import java.util.Set;
137import java.util.concurrent.ConcurrentHashMap;
138import java.util.concurrent.ConcurrentLinkedQueue;
139import java.util.concurrent.Executors;
140import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800141import java.util.concurrent.TimeUnit;
142import java.util.concurrent.atomic.AtomicBoolean;
143import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700144
Charles Chand6d25332016-02-26 22:19:52 -0800145import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800146import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700147import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800148import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
149import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chand6d25332016-02-26 22:19:52 -0800150
Charles Chanb7f75ac2016-01-11 18:28:54 -0800151/**
152 * Segment routing manager.
153 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700154@Service
155@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700156public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700157
Charles Chan46fdfaf2016-11-09 20:51:44 -0800158 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700159 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700162 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800165 private NeighbourResolutionService neighbourResolutionService;
166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100168 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700169
170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700171 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700174 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan873661e2017-11-30 15:37:50 -0800177 HostLocationProbingService probingService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100180 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800183 DeviceAdminService deviceAdminService;
184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800186 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700187
188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100189 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700190
Charles Chan82ab1932016-01-30 23:22:37 -0800191 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800192 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700193
194 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800195 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700196
197 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100198 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700199
200 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan83163812018-01-09 13:45:07 -0800201 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700202
203 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700204 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800205
206 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800207 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800208
Saurav Dasc3604f12016-03-23 11:22:49 -0700209 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800210 public InterfaceService interfaceService;
211
Pier Luigi580fd8a2018-01-16 10:47:50 +0100212 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
213 public ClusterService clusterService;
214
215 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
216 public LeadershipService leadershipService;
217
Charles Chan873661e2017-11-30 15:37:50 -0800218 @Property(name = "activeProbing", boolValue = true,
219 label = "Enable active probing to discover dual-homed hosts.")
220 boolean activeProbing = true;
221
Charles Chandebfea32016-10-24 14:52:01 -0700222 ArpHandler arpHandler = null;
223 IcmpHandler icmpHandler = null;
224 IpHandler ipHandler = null;
225 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700226 ApplicationId appId;
227 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700228
Charles Chandebfea32016-10-24 14:52:01 -0700229 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700230 private TunnelHandler tunnelHandler = null;
231 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700232 private InternalPacketProcessor processor = null;
233 private InternalLinkListener linkListener = null;
234 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700235 private AppConfigHandler appCfgHandler = null;
Pier Luigi69f774d2018-02-28 12:10:50 +0100236 public XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800237 McastHandler mcastHandler = null;
238 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800239 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800240 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800241 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800242 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100243 private TopologyHandler topologyHandler = null;
sangho80f11cb2015-04-01 13:05:26 -0700244 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan82ab1932016-01-30 23:22:37 -0800245 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700246 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
247 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700248 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100249 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sangho80f11cb2015-04-01 13:05:26 -0700250
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700251 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700252 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sangho80f11cb2015-04-01 13:05:26 -0700253
Saurav Das2d94d312015-11-24 23:21:05 -0800254 @SuppressWarnings("rawtypes")
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700255 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Saurav Dase6c448a2018-01-18 12:07:33 -0800256 Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chanb7f75ac2016-01-11 18:28:54 -0800257 new ConcurrentHashMap<>();
258 /**
Saurav Das261c3002017-06-13 15:35:54 -0700259 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700260 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800261 */
Charles Chan873661e2017-11-30 15:37:50 -0800262 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700263 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800264 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700265 * Per device next objective ID store with (device id + vlanid) as key.
266 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800267 */
Charles Chan873661e2017-11-30 15:37:50 -0800268 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800269 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800270 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700271 * Per device next objective ID store with (device id + port + treatment + meta) as key.
272 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800273 */
Charles Chan873661e2017-11-30 15:37:50 -0800274 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800275 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800276
Saurav Das2d94d312015-11-24 23:21:05 -0800277 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
278 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700279
Saurav Das261c3002017-06-13 15:35:54 -0700280 private AtomicBoolean programmingScheduled = new AtomicBoolean();
281
Charles Chanc91c8782016-03-30 17:54:24 -0700282 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700283 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
284 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700285 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700286 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800287 public SegmentRoutingDeviceConfig createConfig() {
288 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700289 }
290 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800291
Charles Chanc91c8782016-03-30 17:54:24 -0700292 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700293 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
294 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700295 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800296 @Override
297 public SegmentRoutingAppConfig createConfig() {
298 return new SegmentRoutingAppConfig();
299 }
300 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800301
Charles Chan82f19972016-05-17 13:13:55 -0700302 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
303 new ConfigFactory<ApplicationId, XConnectConfig>(
304 SubjectFactories.APP_SUBJECT_FACTORY,
305 XConnectConfig.class, "xconnect") {
306 @Override
307 public XConnectConfig createConfig() {
308 return new XConnectConfig();
309 }
310 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800311
Charles Chanc91c8782016-03-30 17:54:24 -0700312 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700313 new ConfigFactory<ApplicationId, McastConfig>(
314 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700315 McastConfig.class, "multicast") {
316 @Override
317 public McastConfig createConfig() {
318 return new McastConfig();
319 }
320 };
321
Charles Chan3ed34d82017-06-22 18:03:14 -0700322 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700323 private static int numOfEventsQueued = 0;
324 private static int numOfEventsExecuted = 0;
sangho80f11cb2015-04-01 13:05:26 -0700325 private static int numOfHandlerExecution = 0;
326 private static int numOfHandlerScheduled = 0;
327
Charles Chan1963f4f2016-02-18 14:22:42 -0800328 /**
329 * Segment Routing App ID.
330 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800331 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan10b0fb72017-02-02 16:20:42 -0800332
Charles Chanb7f75ac2016-01-11 18:28:54 -0800333 /**
334 * The default VLAN ID assigned to the interfaces without subnet config.
335 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800336 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das7c305372015-10-28 12:39:42 -0700337
sangho80f11cb2015-04-01 13:05:26 -0700338 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800339 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800340 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700341
342 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700343 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700344 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700345 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700346 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700347 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700348 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700349 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700350 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700351
Charles Chan10b0fb72017-02-02 16:20:42 -0800352 log.debug("Creating EC map vlannextobjectivestore");
353 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
354 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
355 vlanNextObjStore = vlanNextObjMapBuilder
356 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700357 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700358 .withTimestampProvider((k, v) -> new WallClockTimestamp())
359 .build();
360
Saurav Das2d94d312015-11-24 23:21:05 -0800361 log.debug("Creating EC map subnetnextobjectivestore");
362 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
363 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
364 portNextObjStore = portNextObjMapBuilder
365 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700366 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800367 .withTimestampProvider((k, v) -> new WallClockTimestamp())
368 .build();
369
sangho4a5c42a2015-05-20 22:16:38 -0700370 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
371 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700372 tunnelStore = tunnelMapBuilder
373 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700374 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700375 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700376 .build();
377
378 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
379 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700380 policyStore = policyMapBuilder
381 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700382 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700383 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700384 .build();
385
Saurav Dasc3604f12016-03-23 11:22:49 -0700386 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800387 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700388 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800389 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800390 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
391 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700392 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800393 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700394 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800395 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800396 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
397 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800398 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
399 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700400 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700401 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700402 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
403 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800404 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
405 "staleLinkAge", "15000");
406 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
407 "allowDuplicateIps", "false");
Charles Chan873661e2017-11-30 15:37:50 -0800408 compCfgService.registerProperties(getClass());
409 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700410
Charles Chan2b078ae2015-10-14 11:24:40 -0700411 processor = new InternalPacketProcessor();
412 linkListener = new InternalLinkListener();
413 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700414 appCfgHandler = new AppConfigHandler(this);
415 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700416 mcastHandler = new McastHandler(this);
417 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800418 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700419 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800420 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800421 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigid8a15162018-02-15 16:33:08 +0100422 topologyHandler = new TopologyHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700423
Charles Chand6d25332016-02-26 22:19:52 -0800424 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700425 cfgService.registerConfigFactory(deviceConfigFactory);
426 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700427 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700428 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800429 log.info("Configuring network before adding listeners");
Charles Chan6961f222018-01-04 14:26:07 -0800430 cfgListener.configureNetwork();
431
Charles Chan82ab1932016-01-30 23:22:37 -0800432 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700433 packetService.addProcessor(processor, PacketProcessor.director(2));
434 linkService.addListener(linkListener);
435 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700436 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700437 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100438 topologyService.addListener(topologyListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700439
Charles Chanc12c3d02018-03-09 15:53:44 -0800440 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800441 l2TunnelHandler.init();
442
sangho80f11cb2015-04-01 13:05:26 -0700443 log.info("Started");
444 }
445
Saurav Dase6c448a2018-01-18 12:07:33 -0800446 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700447 return new KryoNamespace.Builder()
448 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700449 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800450 VlanNextObjectiveStoreKey.class,
451 DestinationSet.class,
452 NextNeighbors.class,
453 Tunnel.class,
454 DefaultTunnel.class,
455 Policy.class,
456 TunnelPolicy.class,
457 Policy.Type.class,
458 PortNextObjectiveStoreKey.class,
459 XConnectStoreKey.class,
460 L2Tunnel.class,
461 L2TunnelPolicy.class,
462 DefaultL2Tunnel.class,
463 DefaultL2TunnelPolicy.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700464 );
465 }
466
sangho80f11cb2015-04-01 13:05:26 -0700467 @Deactivate
468 protected void deactivate() {
Charles Chan72f556a2015-10-05 17:50:33 -0700469 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700470 cfgService.unregisterConfigFactory(deviceConfigFactory);
471 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700472 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700473 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800474 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700475
Charles Chanfd48c222017-06-19 00:43:31 -0700476 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700477 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700478 linkService.removeListener(linkListener);
479 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700480 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700481 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100482 topologyService.removeListener(topologyListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700483
Charles Chan2e71ef32017-02-23 15:44:08 -0800484 neighbourResolutionService.unregisterNeighbourHandlers(appId);
485
sangho80f11cb2015-04-01 13:05:26 -0700486 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700487 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700488 deviceListener = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700489 groupHandlerMap.clear();
490
Saurav Das261c3002017-06-13 15:35:54 -0700491 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800492 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700493 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700494 tunnelStore.destroy();
495 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100496
497 mcastHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700498 log.info("Stopped");
499 }
500
Charles Chan873661e2017-11-30 15:37:50 -0800501 @Modified
502 private void modified(ComponentContext context) {
503 Dictionary<?, ?> properties = context.getProperties();
504 if (properties == null) {
505 return;
506 }
507
508 String strActiveProving = Tools.get(properties, "activeProbing");
509 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
510
511 if (expectActiveProbing != activeProbing) {
512 activeProbing = expectActiveProbing;
513 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
514 }
515 }
516
sangho27462c62015-05-14 00:39:53 -0700517 @Override
518 public List<Tunnel> getTunnels() {
519 return tunnelHandler.getTunnels();
520 }
521
522 @Override
sanghobd812f82015-06-29 14:58:47 -0700523 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
524 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700525 }
526
527 @Override
sanghobd812f82015-06-29 14:58:47 -0700528 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700529 for (Policy policy: policyHandler.getPolicies()) {
530 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
531 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
532 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
533 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700534 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700535 }
536 }
537 }
sanghobd812f82015-06-29 14:58:47 -0700538 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700539 }
540
541 @Override
sanghobd812f82015-06-29 14:58:47 -0700542 public PolicyHandler.Result removePolicy(Policy policy) {
543 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700544 }
545
546 @Override
sanghobd812f82015-06-29 14:58:47 -0700547 public PolicyHandler.Result createPolicy(Policy policy) {
548 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700549 }
550
551 @Override
552 public List<Policy> getPolicies() {
553 return policyHandler.getPolicies();
554 }
555
Saurav Das07c74602016-04-27 18:35:50 -0700556 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700557 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
558 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700559 }
560
561 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800562 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700563 return l2TunnelHandler.getL2Tunnels();
564 }
565
566 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800567 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700568 return l2TunnelHandler.getL2Policies();
569 }
570
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700571 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700572 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
573
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700574 // get both added and pending pseudowires
575 List<L2TunnelDescription> pseudowires = new ArrayList<>();
576 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
577 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700578 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700579
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700580 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
581
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700582 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
583 L2TunnelHandler.Result res;
584 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
585 res = addPseudowire(pw);
586 if (res != L2TunnelHandler.Result.SUCCESS) {
587 log.error("Pseudowire with id {} can not be instantiated !", res);
588 retRes = res;
589 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700590 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700591
592 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700593 }
594
595 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800596 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700597 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700598 }
599
600 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800601 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700602 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700603 }
604
605 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700606 public void rerouteNetwork() {
607 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700608 }
609
Charles Chand7844e52016-10-20 17:02:44 -0700610 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800611 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
612 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800613 deviceConfiguration.getRouters().forEach(device ->
614 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700615 return deviceSubnetMap;
616 }
617
Saurav Das62ae6792017-05-15 15:34:25 -0700618
619 @Override
620 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
621 if (defaultRoutingHandler != null) {
622 return defaultRoutingHandler.getCurrentEmcpSpgMap();
623 } else {
624 return null;
625 }
626 }
627
628 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700629 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
630 if (dsNextObjStore != null) {
631 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700632 } else {
633 return ImmutableMap.of();
634 }
635 }
636
Saurav Dasfbe74572017-08-03 18:30:35 -0700637 @Override
638 public void verifyGroups(DeviceId id) {
639 DefaultGroupHandler gh = groupHandlerMap.get(id);
640 if (gh != null) {
641 gh.triggerBucketCorrector();
642 }
643 }
644
Saurav Das6430f412018-01-25 09:49:01 -0800645 @Override
646 public ImmutableMap<Link, Boolean> getSeenLinks() {
647 return linkHandler.getSeenLinks();
648 }
649
650 @Override
651 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
652 return linkHandler.getDownedPorts();
653 }
654
Pier Luigi0f9635b2018-01-15 18:06:43 +0100655 @Override
656 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
657 return mcastHandler.getMcastNextIds(mcastIp);
658 }
659
660 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +0100661 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +0100662 return mcastHandler.getMcastRoles(mcastIp);
663 }
664
665 @Override
666 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
667 return mcastHandler.getMcastPaths(mcastIp);
668 }
669
sangho80f1f892015-05-19 11:57:42 -0700670 /**
Ray Milkeyb85de082017-04-05 09:42:04 -0700671 * Extracts the application ID from the manager.
672 *
673 * @return application ID
674 */
675 public ApplicationId appId() {
676 return appId;
677 }
678
679 /**
680 * Returns the device configuration.
681 *
682 * @return device configuration
683 */
684 public DeviceConfiguration deviceConfiguration() {
685 return deviceConfiguration;
686 }
687
688 /**
Saurav Das261c3002017-06-13 15:35:54 -0700689 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700690 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700691 *
692 * @return next objective ID store
693 */
Saurav Das261c3002017-06-13 15:35:54 -0700694 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
695 dsNextObjStore() {
696 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700697 }
698
699 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700700 * Per device next objective ID store with (device id + vlanid) as key.
701 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700702 *
703 * @return vlan next object store
704 */
705 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
706 return vlanNextObjStore;
707 }
708
709 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700710 * Per device next objective ID store with (device id + port + treatment + meta) as key.
711 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700712 *
713 * @return port next object store.
714 */
715 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
716 return portNextObjStore;
717 }
718
719 /**
Saurav Das261c3002017-06-13 15:35:54 -0700720 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
721 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700722 *
723 * @return MPLS-ECMP value
724 */
725 public boolean getMplsEcmp() {
726 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
727 .getConfig(this.appId, SegmentRoutingAppConfig.class);
728 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
729 }
730
731 /**
sangho80f1f892015-05-19 11:57:42 -0700732 * Returns the tunnel object with the tunnel ID.
733 *
734 * @param tunnelId Tunnel ID
735 * @return Tunnel reference
736 */
sangho27462c62015-05-14 00:39:53 -0700737 public Tunnel getTunnel(String tunnelId) {
738 return tunnelHandler.getTunnel(tunnelId);
739 }
740
Charles Chan90772a72017-02-08 15:52:08 -0800741 // TODO Consider moving these to InterfaceService
sangho80f11cb2015-04-01 13:05:26 -0700742 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800743 * Returns untagged VLAN configured on given connect point.
Charles Chan90772a72017-02-08 15:52:08 -0800744 * <p>
745 * Only returns the first match if there are multiple untagged VLAN configured
746 * on the connect point.
sangho80f11cb2015-04-01 13:05:26 -0700747 *
Charles Chan10b0fb72017-02-02 16:20:42 -0800748 * @param connectPoint connect point
749 * @return untagged VLAN or null if not configured
sangho80f11cb2015-04-01 13:05:26 -0700750 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700751 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800752 return interfaceService.getInterfacesByPort(connectPoint).stream()
753 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
754 .map(Interface::vlanUntagged)
755 .findFirst().orElse(null);
sangho80f11cb2015-04-01 13:05:26 -0700756 }
757
sangho27462c62015-05-14 00:39:53 -0700758 /**
Charles Chan90772a72017-02-08 15:52:08 -0800759 * Returns tagged VLAN configured on given connect point.
760 * <p>
761 * Returns all matches if there are multiple tagged VLAN configured
762 * on the connect point.
763 *
764 * @param connectPoint connect point
765 * @return tagged VLAN or empty set if not configured
766 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700767 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800768 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
769 return interfaces.stream()
770 .map(Interface::vlanTagged)
Charles Chan3ed34d82017-06-22 18:03:14 -0700771 .flatMap(Set::stream)
Charles Chan90772a72017-02-08 15:52:08 -0800772 .collect(Collectors.toSet());
773 }
774
775 /**
776 * Returns native VLAN configured on given connect point.
777 * <p>
778 * Only returns the first match if there are multiple native VLAN configured
779 * on the connect point.
780 *
781 * @param connectPoint connect point
782 * @return native VLAN or null if not configured
783 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700784 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800785 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
786 return interfaces.stream()
787 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
788 .map(Interface::vlanNative)
789 .findFirst()
790 .orElse(null);
791 }
792
793 /**
Charles Chand9265a32017-06-16 15:19:24 -0700794 * Returns internal VLAN for untagged hosts on given connect point.
795 * <p>
796 * The internal VLAN is either vlan-untagged for an access port,
797 * or vlan-native for a trunk port.
798 *
799 * @param connectPoint connect point
800 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
801 */
Pier Luigi69f774d2018-02-28 12:10:50 +0100802 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chand9265a32017-06-16 15:19:24 -0700803 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
804 VlanId nativeVlanId = getNativeVlanId(connectPoint);
805 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
806 }
807
808 /**
Charles Chan3ed34d82017-06-22 18:03:14 -0700809 * Returns optional pair device ID of given device.
810 *
811 * @param deviceId device ID
812 * @return optional pair device ID. Might be empty if pair device is not configured
813 */
814 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
815 SegmentRoutingDeviceConfig deviceConfig =
816 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
817 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
818 }
819 /**
820 * Returns optional pair device local port of given device.
821 *
822 * @param deviceId device ID
823 * @return optional pair device ID. Might be empty if pair device is not configured
824 */
825 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
826 SegmentRoutingDeviceConfig deviceConfig =
827 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
828 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
829 }
830
831 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700832 * Determine if current instance is the master of given connect point.
833 *
834 * @param cp connect point
835 * @return true if current instance is the master of given connect point
836 */
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700837 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan910be6a2017-08-23 14:46:43 -0700838 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
839 if (!isMaster) {
840 log.debug(NOT_MASTER, cp);
841 }
842 return isMaster;
843 }
844
845 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700846 * Returns locations of given resolved route.
847 *
848 * @param resolvedRoute resolved route
849 * @return locations of nexthop. Might be empty if next hop is not found
850 */
851 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
852 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
853 return Optional.ofNullable(hostService.getHost(hostId))
854 .map(Host::locations).orElse(Sets.newHashSet())
855 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
856 }
857
858 /**
Charles Chan90772a72017-02-08 15:52:08 -0800859 * Returns vlan port map of given device.
860 *
861 * @param deviceId device id
862 * @return vlan-port multimap
863 */
864 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
865 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
866
867 interfaceService.getInterfaces().stream()
868 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
869 .forEach(intf -> {
870 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700871 intf.vlanTagged().forEach(vlanTagged ->
872 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
873 );
Charles Chan90772a72017-02-08 15:52:08 -0800874 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
875 });
876 vlanPortMap.removeAll(VlanId.NONE);
877
878 return vlanPortMap;
879 }
880
881 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800882 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800883 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700884 *
885 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800886 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800887 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700888 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700889 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700890 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800891 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
892 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700893 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800894 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800895 + "device {} not found", deviceId);
896 return -1;
897 }
898 }
899
900 /**
901 * Returns the next objective ID for the given portNumber, given the treatment.
902 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700903 * would result in different objectives. If the next object does not exist,
904 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800905 *
906 * @param deviceId Device ID
907 * @param portNum port number on device for which NextObjective is queried
908 * @param treatment the actions to apply on the packets (should include outport)
909 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700910 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700911 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800912 */
913 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
914 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700915 TrafficSelector meta,
916 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800917 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
918 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700919 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800920 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800921 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
922 + " not found", deviceId);
923 return -1;
924 }
925 }
926
Saurav Das62ae6792017-05-15 15:34:25 -0700927 /**
928 * Returns the group handler object for the specified device id.
929 *
930 * @param devId the device identifier
931 * @return the groupHandler object for the device id, or null if not found
932 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700933 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -0700934 return groupHandlerMap.get(devId);
935 }
936
937 /**
Saurav Dasfbe74572017-08-03 18:30:35 -0700938 * Returns the default routing handler object.
939 *
940 * @return the default routing handler object
941 */
942 public DefaultRoutingHandler getRoutingHandler() {
943 return defaultRoutingHandler;
944 }
945
sangho80f11cb2015-04-01 13:05:26 -0700946 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -0700947 @Override
948 public void process(PacketContext context) {
949
950 if (context.isHandled()) {
951 return;
952 }
953
954 InboundPacket pkt = context.inPacket();
955 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -0800956
957 if (ethernet == null) {
958 return;
959 }
960
Saurav Das261c3002017-06-13 15:35:54 -0700961 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
962 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800963 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -0700964 log.warn("Received unexpected ARP packet on {}",
965 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -0700966 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800967 return;
sangho80f11cb2015-04-01 13:05:26 -0700968 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -0800969 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
970 //ipHandler.addToPacketBuffer(ipv4Packet);
971 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
972 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700973 } else {
Charles Chand041ad82017-01-13 17:20:44 -0800974 // NOTE: We don't support IP learning at this moment so this
975 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800976 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700977 }
Pier Ventreb6a7f342016-11-26 21:05:22 -0800978 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
979 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -0800980 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -0800981 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -0800982 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
983 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
984 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
985 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
986 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
987 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700988 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -0700989 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -0800990 }
991 } else {
992 // NOTE: We don't support IP learning at this moment so this
993 // is not necessary. Also it causes duplication of DHCPv6 packets.
994 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
995 }
sangho80f11cb2015-04-01 13:05:26 -0700996 }
997 }
998 }
999
Saurav Das2d94d312015-11-24 23:21:05 -08001000 @SuppressWarnings("rawtypes")
sangho80f11cb2015-04-01 13:05:26 -07001001 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001002 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001003 eventQueue.add(event);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001004 numOfEventsQueued++;
1005
1006 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1007 //No pending scheduled event handling threads. So start a new one.
Charles Chan3f4aca62018-03-21 16:57:47 -07001008 executorService.schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001009 numOfHandlerScheduled++;
1010 }
Jonathan Hart54541d12016-04-12 15:39:44 -07001011 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001012 numOfEventsQueued,
1013 numOfHandlerScheduled);
sangho80f11cb2015-04-01 13:05:26 -07001014 }
sangho80f11cb2015-04-01 13:05:26 -07001015 }
1016
1017 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001018 @Override
sangho80f11cb2015-04-01 13:05:26 -07001019 public void run() {
Pier Luigi8f362362018-02-12 09:56:20 +01001020 while (true) {
1021 try {
Saurav Das2d94d312015-11-24 23:21:05 -08001022 @SuppressWarnings("rawtypes")
Charles Chan3ed34d82017-06-22 18:03:14 -07001023 Event event;
1024 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001025 if (!eventQueue.isEmpty()) {
1026 event = eventQueue.poll();
1027 numOfEventsExecuted++;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001028 } else {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001029 numOfHandlerExecution++;
1030 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1031 numOfHandlerExecution, numOfEventsExecuted);
1032 break;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001033 }
sanghofb7c7292015-04-13 15:15:58 -07001034 }
Pier Luigid8a15162018-02-15 16:33:08 +01001035 // TODO We should also change SR routing and PW to listen to TopologyEvents
Charles Chan0cff8aa2017-03-29 16:39:05 -07001036 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1037 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dase6c448a2018-01-18 12:07:33 -08001038 linkHandler.processLinkAdded((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001039 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Saurav Dase6c448a2018-01-18 12:07:33 -08001040 linkHandler.processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001041 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1042 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1043 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das62af8802015-12-04 10:52:59 -08001044 DeviceId deviceId = ((Device) event.subject()).id();
1045 if (deviceService.isAvailable(deviceId)) {
Saurav Dascea556f2018-03-05 14:37:16 -08001046 log.info("** DEVICE UP Processing device event {} "
1047 + "for available device {}",
Saurav Dasc28b3432015-10-30 17:45:38 -07001048 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001049 processDeviceAdded((Device) event.subject());
Saurav Dasc3604f12016-03-23 11:22:49 -07001050 } else {
Saurav Dascea556f2018-03-05 14:37:16 -08001051 log.info(" ** DEVICE DOWN Processing device event {}"
1052 + " for unavailable device {}",
Pier Luigi8f362362018-02-12 09:56:20 +01001053 event.type(), ((Device) event.subject()).id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001054 processDeviceRemoved((Device) event.subject());
1055 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001056 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001057 // typically these calls come when device is added first time
1058 // so port filtering rules are handled at the device_added event.
1059 // port added calls represent all ports on the device,
1060 // enabled or not.
Saurav Das62ae6792017-05-15 15:34:25 -07001061 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd1872b02016-12-02 15:43:47 -08001062 ((DeviceEvent) event).subject().id(),
1063 ((DeviceEvent) event).port().number(),
1064 event.type());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001065 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001066 // these calls happen for every subsequent event
1067 // ports enabled, disabled, switch goes away, comes back
Saurav Dasf0f592d2016-11-18 15:21:57 -08001068 log.info("** PORT UPDATED {}/{} -> {}",
1069 event.subject(),
1070 ((DeviceEvent) event).port(),
1071 event.type());
1072 processPortUpdated(((Device) event.subject()),
1073 ((DeviceEvent) event).port());
Pier Luigid8a15162018-02-15 16:33:08 +01001074 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1075 // Process topology event, needed for all modules relying on
1076 // topology service for path computation
1077 TopologyEvent topologyEvent = (TopologyEvent) event;
1078 log.info("Processing topology event {}, topology age {}, reasons {}",
1079 event.type(), topologyEvent.subject().time(),
1080 topologyEvent.reasons().size());
1081 topologyHandler.processTopologyChange(topologyEvent.reasons());
Charles Chan3f4aca62018-03-21 16:57:47 -07001082 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1083 hostHandler.processHostAddedEvent((HostEvent) event);
1084 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1085 hostHandler.processHostMovedEvent((HostEvent) event);
1086 routeHandler.processHostMovedEvent((HostEvent) event);
1087 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1088 hostHandler.processHostRemovedEvent((HostEvent) event);
1089 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1090 hostHandler.processHostUpdatedEvent((HostEvent) event);
1091 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1092 routeHandler.processRouteAdded((RouteEvent) event);
1093 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1094 routeHandler.processRouteUpdated((RouteEvent) event);
1095 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1096 routeHandler.processRouteRemoved((RouteEvent) event);
1097 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1098 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
Pier1f87aca2018-03-14 16:47:32 -07001099 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1100 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1101 event.type() == McastEvent.Type.SINKS_ADDED ||
1102 event.type() == McastEvent.Type.SINKS_REMOVED ||
1103 event.type() == McastEvent.Type.ROUTE_ADDED ||
Charles Chan3f4aca62018-03-21 16:57:47 -07001104 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1105 mcastHandler.processMcastEvent((McastEvent) event);
1106 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1107 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1108 Class configClass = netcfgEvent.configClass();
1109 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1110 appCfgHandler.processAppConfigAdded(netcfgEvent);
1111 log.info("App config event .. configuring network");
1112 cfgListener.configureNetwork();
1113 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1114 log.info("Segment Routing Device Config added for {}", event.subject());
1115 cfgListener.configureNetwork();
1116 } else if (configClass.equals(XConnectConfig.class)) {
1117 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1118 } else if (configClass.equals(InterfaceConfig.class)) {
1119 log.info("Interface Config added for {}", event.subject());
1120 cfgListener.configureNetwork();
1121 } else {
1122 log.error("Unhandled config class: {}", configClass);
1123 }
1124 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1125 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1126 Class configClass = netcfgEvent.configClass();
1127 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1128 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1129 log.info("App config event .. configuring network");
1130 cfgListener.configureNetwork();
1131 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1132 log.info("Segment Routing Device Config updated for {}", event.subject());
1133 createOrUpdateDeviceConfiguration();
1134 } else if (configClass.equals(XConnectConfig.class)) {
1135 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1136 } else if (configClass.equals(InterfaceConfig.class)) {
1137 log.info("Interface Config updated for {}", event.subject());
1138 createOrUpdateDeviceConfiguration();
1139 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1140 (InterfaceConfig) netcfgEvent.prevConfig().get());
1141 } else {
1142 log.error("Unhandled config class: {}", configClass);
1143 }
1144 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1145 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1146 Class configClass = netcfgEvent.configClass();
1147 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1148 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1149 log.info("App config event .. configuring network");
1150 cfgListener.configureNetwork();
1151 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1152 // TODO Handle sr device config removal
1153 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1154 } else if (configClass.equals(XConnectConfig.class)) {
1155 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1156 } else if (configClass.equals(InterfaceConfig.class)) {
1157 // TODO Handle interface removal
1158 log.info("InterfaceConfig removal is not handled in current implementation");
1159 } else {
1160 log.error("Unhandled config class: {}", configClass);
1161 }
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001162 } else {
1163 log.warn("Unhandled event type: {}", event.type());
1164 }
Pier Luigi8f362362018-02-12 09:56:20 +01001165 } catch (Exception e) {
1166 log.error("SegmentRouting event handler thread thrown an exception: {}",
1167 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001168 }
1169 }
sangho80f11cb2015-04-01 13:05:26 -07001170 }
1171 }
1172
Saurav Dase6c448a2018-01-18 12:07:33 -08001173 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001174 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001175
1176 // NOTE: Punt ARP/NDP even when the device is not configured.
1177 // Host learning without network config is required for CORD config generator.
1178 routingRulePopulator.populateIpPunts(device.id());
1179 routingRulePopulator.populateArpNdpPunts(device.id());
1180
Charles Chan319d1a22015-11-03 10:42:14 -08001181 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001182 log.warn("Device configuration unavailable. Device {} will be "
1183 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001184 return;
1185 }
Charles Chan72779502016-04-23 17:36:10 -07001186 processDeviceAddedInternal(device.id());
1187 }
1188
1189 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001190 // Irrespective of whether the local is a MASTER or not for this device,
1191 // we need to create a SR-group-handler instance. This is because in a
1192 // multi-instance setup, any instance can initiate forwarding/next-objectives
1193 // for any switch (even if this instance is a SLAVE or not even connected
1194 // to the switch). To handle this, a default-group-handler instance is necessary
1195 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001196 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1197 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001198 DefaultGroupHandler groupHandler;
1199 try {
1200 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001201 createGroupHandler(deviceId,
1202 appId,
1203 deviceConfiguration,
1204 linkService,
1205 flowObjectiveService,
1206 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001207 } catch (DeviceConfigNotFoundException e) {
1208 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1209 return;
1210 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001211 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001212 deviceId);
1213 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001214 }
Saurav Dasb149be12016-06-07 10:08:06 -07001215
Charles Chan72779502016-04-23 17:36:10 -07001216 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001217 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chandebfea32016-10-24 14:52:01 -07001218 hostHandler.init(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001219 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001220 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001221 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001222 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001223 }
Charles Chan82ab1932016-01-30 23:22:37 -08001224
Charles Chandebfea32016-10-24 14:52:01 -07001225 appCfgHandler.init(deviceId);
1226 routeHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001227 }
1228
Saurav Dasc3604f12016-03-23 11:22:49 -07001229 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001230 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001231 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001232 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001233 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001234 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001235 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001236 portNextObjStore.entrySet().stream()
1237 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001238 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001239 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001240
Saurav Dasfbe74572017-08-03 18:30:35 -07001241 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1242 if (gh != null) {
1243 gh.shutdown();
1244 }
Saurav Das62ae6792017-05-15 15:34:25 -07001245 // Note that a switch going down is associated with all of its links
1246 // going down as well, but it is treated as a single switch down event
1247 // while the link-downs are ignored.
1248 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001249 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001250 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001251 xConnectHandler.removeDevice(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001252
1253 // Cleanup all internal groupHandler stores for this device. Should be
1254 // done after all rerouting or rehashing has been completed
1255 groupHandlerMap.entrySet()
1256 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001257 }
1258
Saurav Dasf0f592d2016-11-18 15:21:57 -08001259 private void processPortUpdated(Device device, Port port) {
1260 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1261 log.warn("Device configuration uploading. Not handling port event for"
1262 + "dev: {} port: {}", device.id(), port.number());
1263 return;
1264 }
Saurav Dasf9332192017-02-18 14:05:44 -08001265
1266 if (!mastershipService.isLocalMaster(device.id())) {
1267 log.debug("Not master for dev:{} .. not handling port updated event"
1268 + "for port {}", device.id(), port.number());
1269 return;
1270 }
1271
1272 // first we handle filtering rules associated with the port
1273 if (port.isEnabled()) {
1274 log.info("Switchport {}/{} enabled..programming filters",
1275 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001276 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001277 } else {
1278 log.info("Switchport {}/{} disabled..removing filters",
1279 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001280 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001281 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001282
1283 // portUpdated calls are for ports that have gone down or up. For switch
1284 // to switch ports, link-events should take care of any re-routing or
1285 // group editing necessary for port up/down. Here we only process edge ports
1286 // that are already configured.
Saurav Das3fb28272017-03-04 16:08:47 -08001287 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1288 VlanId untaggedVlan = getUntaggedVlanId(cp);
1289 VlanId nativeVlan = getNativeVlanId(cp);
1290 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001291
Saurav Das3fb28272017-03-04 16:08:47 -08001292 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001293 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001294 + "dev/port: {}/{}", device.id(), port.number());
1295 return;
1296 }
Saurav Das3fb28272017-03-04 16:08:47 -08001297 if (untaggedVlan != null) {
1298 processEdgePort(device, port, untaggedVlan, true);
1299 }
1300 if (nativeVlan != null) {
1301 processEdgePort(device, port, nativeVlan, true);
1302 }
1303 if (!taggedVlans.isEmpty()) {
1304 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1305 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001306 }
1307
Saurav Das3fb28272017-03-04 16:08:47 -08001308 private void processEdgePort(Device device, Port port, VlanId vlanId,
1309 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001310 boolean portUp = port.isEnabled();
1311 if (portUp) {
Saurav Das3fb28272017-03-04 16:08:47 -08001312 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001313 port.number(), vlanId);
Charles Chan873661e2017-11-30 15:37:50 -08001314 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001315 } else {
Saurav Das3fb28272017-03-04 16:08:47 -08001316 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001317 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001318 }
1319
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001320 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sangho80f11cb2015-04-01 13:05:26 -07001321 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001322 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001323 } else {
1324 log.warn("Group handler not found for dev:{}. Not handling edge port"
1325 + " {} event for port:{}", device.id(),
1326 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001327 }
1328 }
sangho27462c62015-05-14 00:39:53 -07001329
Charles Chan8ca5a122017-10-20 16:06:55 -07001330 private void createOrUpdateDeviceConfiguration() {
1331 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001332 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001333 deviceConfiguration = new DeviceConfiguration(this);
1334 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001335 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001336 deviceConfiguration.updateConfig();
1337 }
1338 }
1339
Pier Ventreb6a7f342016-11-26 21:05:22 -08001340 /**
1341 * Registers the given connect point with the NRS, this is necessary
1342 * to receive the NDP and ARP packets from the NRS.
1343 *
1344 * @param portToRegister connect point to register
1345 */
1346 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001347 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001348 portToRegister,
1349 neighbourHandler,
1350 appId
1351 );
1352 }
1353
Charles Chan72f556a2015-10-05 17:50:33 -07001354 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001355 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001356 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001357
Charles Chanb7f75ac2016-01-11 18:28:54 -08001358 /**
1359 * Constructs the internal network config listener.
1360 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001361 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001362 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001363 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001364 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001365 }
1366
Charles Chanb7f75ac2016-01-11 18:28:54 -08001367 /**
1368 * Reads network config and initializes related data structure accordingly.
1369 */
Charles Chan873661e2017-11-30 15:37:50 -08001370 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001371 log.info("Configuring network ...");
Charles Chan8ca5a122017-10-20 16:06:55 -07001372 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001373
Charles Chan46fdfaf2016-11-09 20:51:44 -08001374 arpHandler = new ArpHandler(srManager);
1375 icmpHandler = new IcmpHandler(srManager);
1376 ipHandler = new IpHandler(srManager);
1377 routingRulePopulator = new RoutingRulePopulator(srManager);
1378 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chane7c61022015-10-07 14:21:45 -07001379
1380 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1381 groupHandlerMap, tunnelStore);
1382 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1383 flowObjectiveService,
1384 tunnelHandler, policyStore);
Saurav Das261c3002017-06-13 15:35:54 -07001385 // add a small delay to absorb multiple network config added notifications
1386 if (!programmingScheduled.get()) {
Saurav Dase321cff2018-02-09 17:26:45 -08001387 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das261c3002017-06-13 15:35:54 -07001388 programmingScheduled.set(true);
1389 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1390 TimeUnit.SECONDS);
Charles Chane7c61022015-10-07 14:21:45 -07001391 }
Charles Chan72779502016-04-23 17:36:10 -07001392 mcastHandler.init();
Charles Chane7c61022015-10-07 14:21:45 -07001393 }
1394
Charles Chan72f556a2015-10-05 17:50:33 -07001395 @Override
1396 public void event(NetworkConfigEvent event) {
Charles Chan3f4aca62018-03-21 16:57:47 -07001397 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1398 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1399 switch (event.type()) {
1400 case CONFIG_ADDED:
1401 case CONFIG_UPDATED:
1402 case CONFIG_REMOVED:
1403 log.trace("Schedule Network Config event {}", event);
1404 scheduleEventHandlerIfNotScheduled(event);
1405 break;
1406 default:
1407 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001408 }
1409 }
Saurav Das261c3002017-06-13 15:35:54 -07001410
Charles Chanc4a68c32018-01-03 16:26:32 -08001411 @Override
1412 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001413 if (event.type() == CONFIG_REGISTERED ||
1414 event.type() == CONFIG_UNREGISTERED) {
1415 log.debug("Ignore event {} due to type mismatch", event);
1416 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001417 }
Saurav Dase321cff2018-02-09 17:26:45 -08001418
1419 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1420 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1421 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -08001422 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001423 log.debug("Ignore event {} due to class mismatch", event);
1424 return false;
1425 }
1426
1427 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001428 }
1429
Saurav Das261c3002017-06-13 15:35:54 -07001430 private final class ConfigChange implements Runnable {
1431 @Override
1432 public void run() {
1433 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001434 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001435 for (Device device : deviceService.getDevices()) {
1436 processDeviceAdded(device);
1437 }
1438 defaultRoutingHandler.startPopulationProcess();
1439 }
1440 }
Charles Chan72f556a2015-10-05 17:50:33 -07001441 }
Charles Chanf4586112015-11-09 16:37:23 -08001442
Charles Chan3f4aca62018-03-21 16:57:47 -07001443 private class InternalLinkListener implements LinkListener {
1444 @Override
1445 public void event(LinkEvent event) {
1446 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1447 event.type() == LinkEvent.Type.LINK_UPDATED ||
1448 event.type() == LinkEvent.Type.LINK_REMOVED) {
1449 log.trace("Schedule Link event {}", event);
1450 scheduleEventHandlerIfNotScheduled(event);
1451 }
1452 }
1453 }
1454
1455 private class InternalDeviceListener implements DeviceListener {
1456 @Override
1457 public void event(DeviceEvent event) {
1458 switch (event.type()) {
1459 case DEVICE_ADDED:
1460 case PORT_UPDATED:
1461 case PORT_ADDED:
1462 case DEVICE_UPDATED:
1463 case DEVICE_AVAILABILITY_CHANGED:
1464 log.trace("Schedule Device event {}", event);
1465 scheduleEventHandlerIfNotScheduled(event);
1466 break;
1467 default:
1468 }
1469 }
1470 }
1471
1472 private class InternalTopologyListener implements TopologyListener {
1473 @Override
1474 public void event(TopologyEvent event) {
1475 switch (event.type()) {
1476 case TOPOLOGY_CHANGED:
1477 log.trace("Schedule Topology event {}", event);
1478 scheduleEventHandlerIfNotScheduled(event);
1479 break;
1480 default:
1481 }
1482 }
1483 }
1484
Charles Chanf4586112015-11-09 16:37:23 -08001485 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001486 @Override
1487 public void event(HostEvent event) {
Charles Chanf4586112015-11-09 16:37:23 -08001488 switch (event.type()) {
1489 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001490 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001491 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001492 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001493 log.trace("Schedule Host event {}", event);
1494 scheduleEventHandlerIfNotScheduled(event);
Charles Chanf4586112015-11-09 16:37:23 -08001495 break;
1496 default:
1497 log.warn("Unsupported host event type: {}", event.type());
1498 break;
1499 }
1500 }
1501 }
1502
Charles Chanc91c8782016-03-30 17:54:24 -07001503 private class InternalMcastListener implements McastListener {
1504 @Override
1505 public void event(McastEvent event) {
1506 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07001507 case SOURCES_ADDED:
1508 case SOURCES_REMOVED:
1509 case SINKS_ADDED:
1510 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07001511 case ROUTE_REMOVED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001512 log.trace("Schedule Mcast event {}", event);
1513 scheduleEventHandlerIfNotScheduled(event);
Pier Luigi6786b922018-02-02 16:19:11 +01001514 break;
1515 case ROUTE_ADDED:
Charles Chanc91c8782016-03-30 17:54:24 -07001516 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001517 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07001518 break;
1519 }
1520 }
1521 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001522
Charles Chandebfea32016-10-24 14:52:01 -07001523 private class InternalRouteEventListener implements RouteListener {
1524 @Override
1525 public void event(RouteEvent event) {
1526 switch (event.type()) {
1527 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07001528 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07001529 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07001530 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001531 log.trace("Schedule Route event {}", event);
1532 scheduleEventHandlerIfNotScheduled(event);
Charles Chan910be6a2017-08-23 14:46:43 -07001533 break;
Charles Chandebfea32016-10-24 14:52:01 -07001534 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001535 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07001536 break;
1537 }
1538 }
1539 }
Saurav Das62ae6792017-05-15 15:34:25 -07001540
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001541 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1542 try {
1543 Set<Interface> intfs = conf.getInterfaces();
1544 Set<Interface> prevIntfs = prevConf.getInterfaces();
1545
1546 // Now we only handle one interface config at each port.
1547 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1548 log.warn("Interface update aborted - one at a time is allowed, " +
1549 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1550 return;
1551 }
1552
1553 Interface intf = intfs.stream().findFirst().get();
1554 Interface prevIntf = prevIntfs.stream().findFirst().get();
1555
1556 DeviceId deviceId = intf.connectPoint().deviceId();
1557 PortNumber portNum = intf.connectPoint().port();
1558
1559 if (!mastershipService.isLocalMaster(deviceId)) {
1560 log.debug("CONFIG_UPDATED event for interfaces should be " +
1561 "handled by master node for device {}", deviceId);
1562 return;
1563 }
1564
1565 removeSubnetConfig(prevIntf.connectPoint(),
1566 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1567 new HashSet<>(intf.ipAddressesList())));
1568
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001569 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1570 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1571 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1572 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1573 // Update filtering objective and L2IG group bucket
1574 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1575 } else {
1576 // RemoveVlanNative
1577 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1578 }
1579 }
1580
1581 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1582 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1583 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1584 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1585 // Update filtering objective and L2IG group bucket
1586 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1587 } else {
1588 // RemoveVlanUntagged
1589 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1590 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001591 }
1592
1593 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1594 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001595 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1596 .filter(i -> !intf.vlanUntagged().equals(i))
1597 .filter(i -> !intf.vlanNative().equals(i))
1598 .forEach(vlanId -> updateVlanConfigInternal(
1599 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001600 }
1601
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001602 if (!intf.vlanNative().equals(VlanId.NONE)
1603 && !prevIntf.vlanNative().equals(intf.vlanNative())
1604 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1605 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1606 // Update filtering objective and L2IG group bucket
1607 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1608 } else {
1609 // AddVlanNative
1610 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1611 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001612 }
1613
1614 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1615 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001616 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1617 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1618 .filter(i -> !prevIntf.vlanNative().equals(i))
1619 .forEach(vlanId -> updateVlanConfigInternal(
1620 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001621 );
1622 }
1623
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001624 if (!intf.vlanUntagged().equals(VlanId.NONE)
1625 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1626 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1627 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1628 // Update filtering objective and L2IG group bucket
1629 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1630 } else {
1631 // AddVlanUntagged
1632 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1633 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001634 }
1635 addSubnetConfig(prevIntf.connectPoint(),
1636 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1637 new HashSet<>(prevIntf.ipAddressesList())));
1638 } catch (ConfigException e) {
1639 log.error("Error in configuration");
1640 }
1641 }
1642
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001643 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1644 VlanId vlanId, boolean pushVlan) {
1645 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1646 if (grpHandler == null) {
1647 log.warn("Failed to retrieve group handler for device {}", deviceId);
1648 return;
1649 }
1650
1651 // Update filtering objective for a single port
1652 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1653 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1654
1655 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1656 // Update L2IG bucket of the port
1657 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1658 } else {
1659 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1660 }
1661 }
1662
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001663 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1664 VlanId vlanId, boolean pushVlan, boolean install) {
1665 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1666 if (grpHandler == null) {
1667 log.warn("Failed to retrieve group handler for device {}", deviceId);
1668 return;
1669 }
1670
1671 // Update filtering objective for a single port
1672 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1673
1674 // Update filtering objective for multicast ingress port
1675 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1676
1677 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1678
1679 if (nextId != -1 && !install) {
1680 // Update next objective for a single port as an output port
1681 // Remove a single port from L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001682 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001683 // Remove L2 Bridging rule and L3 Unicast rule to the host
1684 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1685 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1686 // only if there is no port configured on that VLAN ID
1687 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1688 // Remove broadcast forwarding rule for the VLAN
1689 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1690 // Remove L2FG for VLAN
1691 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1692 } else {
1693 // Remove L2IG of the port
1694 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1695 }
1696 } else if (install) {
1697 if (nextId != -1) {
1698 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001699 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001700 } else {
1701 // Create L2FG for VLAN
1702 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1703 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1704 }
1705 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1706 } else {
1707 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1708 }
1709 }
1710
1711 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1712 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1713 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1714
1715 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1716 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1717 .filter(intf -> !intf.connectPoint().equals(cp))
1718 .flatMap(intf -> intf.ipAddressesList().stream())
1719 .collect(Collectors.toSet());
1720 // 1. Partial subnet population
1721 // Remove routing rules for removed subnet from previous configuration,
1722 // which does not also exist in other interfaces in the same device
1723 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1724 .map(InterfaceIpAddress::subnetAddress)
1725 .collect(Collectors.toSet());
1726
1727 defaultRoutingHandler.revokeSubnet(
1728 ipPrefixSet.stream()
1729 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1730 .collect(Collectors.toSet()));
1731
1732 // 2. Interface IP punts
1733 // Remove IP punts for old Intf address
1734 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1735 .map(InterfaceIpAddress::ipAddress)
1736 .collect(Collectors.toSet());
1737 ipAddressSet.stream()
1738 .map(InterfaceIpAddress::ipAddress)
1739 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1740 .forEach(interfaceIpAddress ->
1741 routingRulePopulator.revokeSingleIpPunts(
1742 cp.deviceId(), interfaceIpAddress));
1743
1744 // 3. Host unicast routing rule
1745 // Remove unicast routing rule
1746 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1747 }
1748
1749 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1750 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1751 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1752
1753 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1754 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1755 .filter(intf -> !intf.connectPoint().equals(cp))
1756 .flatMap(intf -> intf.ipAddressesList().stream())
1757 .collect(Collectors.toSet());
1758 // 1. Partial subnet population
1759 // Add routing rules for newly added subnet, which does not also exist in
1760 // other interfaces in the same device
1761 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1762 .map(InterfaceIpAddress::subnetAddress)
1763 .collect(Collectors.toSet());
1764
1765 defaultRoutingHandler.populateSubnet(
1766 Collections.singleton(cp),
1767 ipPrefixSet.stream()
1768 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1769 .collect(Collectors.toSet()));
1770
1771 // 2. Interface IP punts
1772 // Add IP punts for new Intf address
1773 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1774 .map(InterfaceIpAddress::ipAddress)
1775 .collect(Collectors.toSet());
1776 ipAddressSet.stream()
1777 .map(InterfaceIpAddress::ipAddress)
1778 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1779 .forEach(interfaceIpAddress ->
1780 routingRulePopulator.populateSingleIpPunts(
1781 cp.deviceId(), interfaceIpAddress));
1782
1783 // 3. Host unicast routing rule
1784 // Add unicast routing rule
1785 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1786 }
sangho80f11cb2015-04-01 13:05:26 -07001787}