blob: a47101daeb4081a164d213e766692bffe8415a24 [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;
Pier Ventreb6a7f342016-11-26 21:05:22 -080047import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070048import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070050import org.onosproject.net.Host;
51import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070052import org.onosproject.net.Link;
53import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080054import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070055import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070056import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070058import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070059import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070060import org.onosproject.net.config.basics.InterfaceConfig;
61import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070062import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080063import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070064import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080067import org.onosproject.net.flow.TrafficSelector;
68import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070069import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080070import org.onosproject.net.host.HostEvent;
71import org.onosproject.net.host.HostListener;
Charles Chan873661e2017-11-30 15:37:50 -080072import org.onosproject.net.host.HostLocationProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080073import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070074import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyae0068a2017-08-15 11:02:29 -070075import org.onosproject.net.intf.Interface;
76import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080077import org.onosproject.net.link.LinkEvent;
78import org.onosproject.net.link.LinkListener;
79import org.onosproject.net.link.LinkService;
Charles Chanc91c8782016-03-30 17:54:24 -070080import org.onosproject.net.mcast.McastEvent;
81import org.onosproject.net.mcast.McastListener;
82import org.onosproject.net.mcast.MulticastRouteService;
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;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700103import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800104import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700105import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800106import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
107
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800108import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700109import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800111import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
112
Saurav Das261c3002017-06-13 15:35:54 -0700113import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigi0f9635b2018-01-15 18:06:43 +0100114import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700115import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800116import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700117import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hart54541d12016-04-12 15:39:44 -0700118import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700119import org.onosproject.store.service.EventuallyConsistentMap;
120import org.onosproject.store.service.EventuallyConsistentMapBuilder;
121import org.onosproject.store.service.StorageService;
122import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800123import org.osgi.service.component.ComponentContext;
sangho80f11cb2015-04-01 13:05:26 -0700124import org.slf4j.Logger;
125import org.slf4j.LoggerFactory;
126
Jonathan Hart61e24e12017-11-30 18:23:42 -0800127import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800128import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800129import java.util.HashSet;
130import java.util.List;
131import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800132import java.util.Optional;
133import java.util.Set;
134import java.util.concurrent.ConcurrentHashMap;
135import java.util.concurrent.ConcurrentLinkedQueue;
136import java.util.concurrent.Executors;
137import java.util.concurrent.ScheduledExecutorService;
138import java.util.concurrent.ScheduledFuture;
139import java.util.concurrent.TimeUnit;
140import java.util.concurrent.atomic.AtomicBoolean;
141import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700142
Charles Chand6d25332016-02-26 22:19:52 -0800143import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800144import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700145import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800146import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
147import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800148import static org.onosproject.segmentrouting.pwaas.PwaasUtil.configurationValidity;
Charles Chand6d25332016-02-26 22:19:52 -0800149
Charles Chanb7f75ac2016-01-11 18:28:54 -0800150/**
151 * Segment routing manager.
152 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700153@Service
154@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700155public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700156
Charles Chan46fdfaf2016-11-09 20:51:44 -0800157 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700158 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700161 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800164 private NeighbourResolutionService neighbourResolutionService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700167 CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700170 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700173 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan873661e2017-11-30 15:37:50 -0800176 HostLocationProbingService probingService;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700179 DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800182 DeviceAdminService deviceAdminService;
183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800185 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700188 LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700189
Charles Chan82ab1932016-01-30 23:22:37 -0800190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800191 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800194 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
197 MulticastRouteService multicastRouteService;
198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan83163812018-01-09 13:45:07 -0800200 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700203 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800204
205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800206 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800207
Saurav Dasc3604f12016-03-23 11:22:49 -0700208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800209 public InterfaceService interfaceService;
210
Pier Luigi580fd8a2018-01-16 10:47:50 +0100211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
212 public ClusterService clusterService;
213
214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
215 public LeadershipService leadershipService;
216
Charles Chan873661e2017-11-30 15:37:50 -0800217 @Property(name = "activeProbing", boolValue = true,
218 label = "Enable active probing to discover dual-homed hosts.")
219 boolean activeProbing = true;
220
Charles Chandebfea32016-10-24 14:52:01 -0700221 ArpHandler arpHandler = null;
222 IcmpHandler icmpHandler = null;
223 IpHandler ipHandler = null;
224 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700225 ApplicationId appId;
226 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700227
Charles Chandebfea32016-10-24 14:52:01 -0700228 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700229 private TunnelHandler tunnelHandler = null;
230 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700231 private InternalPacketProcessor processor = null;
232 private InternalLinkListener linkListener = null;
233 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700234 private AppConfigHandler appCfgHandler = null;
Charles Chandebfea32016-10-24 14:52:01 -0700235 XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800236 McastHandler mcastHandler = null;
237 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800238 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800239 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800240 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800241 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100242 private TopologyHandler topologyHandler = null;
sangho80f11cb2015-04-01 13:05:26 -0700243 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan82ab1932016-01-30 23:22:37 -0800244 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700245 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
246 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700247 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100248 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sangho80f11cb2015-04-01 13:05:26 -0700249
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700250 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700251 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sangho80f11cb2015-04-01 13:05:26 -0700252
Saurav Das2d94d312015-11-24 23:21:05 -0800253 @SuppressWarnings("unused")
sangho80f11cb2015-04-01 13:05:26 -0700254 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das2d94d312015-11-24 23:21:05 -0800255 @SuppressWarnings("rawtypes")
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700256 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Saurav Dase6c448a2018-01-18 12:07:33 -0800257 Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chanb7f75ac2016-01-11 18:28:54 -0800258 new ConcurrentHashMap<>();
259 /**
Saurav Das261c3002017-06-13 15:35:54 -0700260 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700261 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800262 */
Charles Chan873661e2017-11-30 15:37:50 -0800263 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700264 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800265 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700266 * Per device next objective ID store with (device id + vlanid) as key.
267 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800268 */
Charles Chan873661e2017-11-30 15:37:50 -0800269 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800270 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800271 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700272 * Per device next objective ID store with (device id + port + treatment + meta) as key.
273 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800274 */
Charles Chan873661e2017-11-30 15:37:50 -0800275 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800276 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800277
Saurav Das2d94d312015-11-24 23:21:05 -0800278 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
279 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700280
Saurav Das261c3002017-06-13 15:35:54 -0700281 private AtomicBoolean programmingScheduled = new AtomicBoolean();
282
Charles Chanc91c8782016-03-30 17:54:24 -0700283 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700284 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
285 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700286 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700287 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800288 public SegmentRoutingDeviceConfig createConfig() {
289 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700290 }
291 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800292
Charles Chanc91c8782016-03-30 17:54:24 -0700293 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700294 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
295 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700296 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800297 @Override
298 public SegmentRoutingAppConfig createConfig() {
299 return new SegmentRoutingAppConfig();
300 }
301 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800302
Charles Chan82f19972016-05-17 13:13:55 -0700303 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
304 new ConfigFactory<ApplicationId, XConnectConfig>(
305 SubjectFactories.APP_SUBJECT_FACTORY,
306 XConnectConfig.class, "xconnect") {
307 @Override
308 public XConnectConfig createConfig() {
309 return new XConnectConfig();
310 }
311 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800312
Charles Chanc91c8782016-03-30 17:54:24 -0700313 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700314 new ConfigFactory<ApplicationId, McastConfig>(
315 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700316 McastConfig.class, "multicast") {
317 @Override
318 public McastConfig createConfig() {
319 return new McastConfig();
320 }
321 };
322
Charles Chan3ed34d82017-06-22 18:03:14 -0700323 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700324 private static int numOfEventsQueued = 0;
325 private static int numOfEventsExecuted = 0;
sangho80f11cb2015-04-01 13:05:26 -0700326 private static int numOfHandlerExecution = 0;
327 private static int numOfHandlerScheduled = 0;
328
Charles Chan1963f4f2016-02-18 14:22:42 -0800329 /**
330 * Segment Routing App ID.
331 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800332 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan10b0fb72017-02-02 16:20:42 -0800333
Charles Chanb7f75ac2016-01-11 18:28:54 -0800334 /**
335 * The default VLAN ID assigned to the interfaces without subnet config.
336 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800337 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das7c305372015-10-28 12:39:42 -0700338
sangho80f11cb2015-04-01 13:05:26 -0700339 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800340 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800341 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700342
343 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700344 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700345 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700346 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700347 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700348 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700349 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700350 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700351 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700352
Charles Chan10b0fb72017-02-02 16:20:42 -0800353 log.debug("Creating EC map vlannextobjectivestore");
354 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
355 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
356 vlanNextObjStore = vlanNextObjMapBuilder
357 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700358 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700359 .withTimestampProvider((k, v) -> new WallClockTimestamp())
360 .build();
361
Saurav Das2d94d312015-11-24 23:21:05 -0800362 log.debug("Creating EC map subnetnextobjectivestore");
363 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
364 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
365 portNextObjStore = portNextObjMapBuilder
366 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700367 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800368 .withTimestampProvider((k, v) -> new WallClockTimestamp())
369 .build();
370
sangho4a5c42a2015-05-20 22:16:38 -0700371 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
372 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700373 tunnelStore = tunnelMapBuilder
374 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700375 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700376 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700377 .build();
378
379 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
380 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700381 policyStore = policyMapBuilder
382 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700383 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700384 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700385 .build();
386
Saurav Dasc3604f12016-03-23 11:22:49 -0700387 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800388 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700389 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800390 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800391 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
392 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700393 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800394 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700395 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800396 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800397 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
398 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800399 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
400 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700401 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700402 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700403 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
404 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800405 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
406 "staleLinkAge", "15000");
407 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
408 "allowDuplicateIps", "false");
Charles Chan873661e2017-11-30 15:37:50 -0800409 compCfgService.registerProperties(getClass());
410 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700411
Charles Chan2b078ae2015-10-14 11:24:40 -0700412 processor = new InternalPacketProcessor();
413 linkListener = new InternalLinkListener();
414 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700415 appCfgHandler = new AppConfigHandler(this);
416 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700417 mcastHandler = new McastHandler(this);
418 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800419 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700420 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800421 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800422 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigid8a15162018-02-15 16:33:08 +0100423 topologyHandler = new TopologyHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700424
Charles Chand6d25332016-02-26 22:19:52 -0800425 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700426 cfgService.registerConfigFactory(deviceConfigFactory);
427 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700428 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700429 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800430 log.info("Configuring network before adding listeners");
Charles Chan6961f222018-01-04 14:26:07 -0800431 cfgListener.configureNetwork();
432
Charles Chan82ab1932016-01-30 23:22:37 -0800433 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700434 packetService.addProcessor(processor, PacketProcessor.director(2));
435 linkService.addListener(linkListener);
436 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700437 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700438 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100439 topologyService.addListener(topologyListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700440
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 Pantelopoulos4c7de132018-02-22 12:32:42 -0800557 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700558 return l2TunnelHandler.getL2Tunnels();
559 }
560
561 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800562 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700563 return l2TunnelHandler.getL2Policies();
564 }
565
566 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800567 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
568
569 List<L2Tunnel> tunnels = getL2Tunnels();
570 List<L2TunnelPolicy> policies = getL2Policies();
571
572 // combine polices and tunnels to pseudowires
573 List<L2TunnelDescription> pseudowires = tunnels.stream()
574 .map(l2Tunnel -> {
575 L2TunnelPolicy policy = null;
576 for (L2TunnelPolicy l2Policy : policies) {
577 if (l2Policy.tunnelId() == l2Tunnel.tunnelId()) {
578 policy = l2Policy;
579 break;
580 }
581 }
582
583 return new DefaultL2TunnelDescription(l2Tunnel, policy);
584 })
585 .collect(Collectors.toList());
586
587
588 // creating a new list with the new pseudowire
589 Set<L2TunnelDescription> newPseudowires = new HashSet<>(pseudowires);
590
591 // corner case where we try to add the exact same pseudowire
592 if (newPseudowires.contains(l2TunnelDescription)) {
593 log.info("Pseudowire with {} already exists!", l2TunnelDescription);
594 return L2TunnelHandler.Result.SUCCESS;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700595 }
596
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800597 // add the new pseudowire to the Set
598 newPseudowires.add(l2TunnelDescription);
599
600 // validate the new set of pseudowires
601 boolean res = configurationValidity(newPseudowires);
602 if (res) {
603
604 // deploy a set with ONLY the new pseudowire
605 newPseudowires = new HashSet<>();
606 newPseudowires.add(l2TunnelDescription);
607 l2TunnelHandler.deploy(newPseudowires);
608
609 log.info("Pseudowire with {} deployment started, check log for any errors in this process!",
610 l2TunnelDescription.l2Tunnel().tunnelId());
611 return L2TunnelHandler.Result.SUCCESS;
612 } else {
613
614 log.error("Pseudowire with {} can not be added!", l2TunnelDescription.l2Tunnel().tunnelId());
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700615 return L2TunnelHandler.Result.ADDITION_ERROR;
616 }
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700617 }
618
619 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800620 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700621
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800622 List<L2Tunnel> tunnels = getL2Tunnels();
623 List<L2TunnelPolicy> policies = getL2Policies();
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700624
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800625 // get the pseudowire, if it exists
626 List<L2TunnelDescription> pseudowires = tunnels.stream().map(l2Tunnel -> {
627 L2TunnelPolicy policy = null;
628 for (L2TunnelPolicy l2Policy : policies) {
629 if (l2Policy.tunnelId() == l2Tunnel.tunnelId()) {
630 policy = l2Policy;
631 break;
632 }
633 }
634
635 return new DefaultL2TunnelDescription(l2Tunnel, policy);
636 }).filter(l2desc ->
637 l2desc.l2Tunnel().tunnelId() == pwId
638 ).collect(Collectors.toList());
639
640 if (pseudowires.size() == 0) {
641 log.error("Pseudowire with id {} does not exist", pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700642 return L2TunnelHandler.Result.REMOVAL_ERROR;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800643 } else {
644
645 l2TunnelHandler.tearDown(new HashSet<>(pseudowires));
646
647 log.info("Removal of pseudowire with {} started, check log for any errors in this process!",
648 pwId);
649 return L2TunnelHandler.Result.SUCCESS;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700650 }
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700651 }
652
653 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700654 public void rerouteNetwork() {
655 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700656 }
657
Charles Chand7844e52016-10-20 17:02:44 -0700658 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800659 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
660 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800661 deviceConfiguration.getRouters().forEach(device ->
662 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700663 return deviceSubnetMap;
664 }
665
Saurav Das62ae6792017-05-15 15:34:25 -0700666
667 @Override
668 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
669 if (defaultRoutingHandler != null) {
670 return defaultRoutingHandler.getCurrentEmcpSpgMap();
671 } else {
672 return null;
673 }
674 }
675
676 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700677 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
678 if (dsNextObjStore != null) {
679 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700680 } else {
681 return ImmutableMap.of();
682 }
683 }
684
Saurav Dasfbe74572017-08-03 18:30:35 -0700685 @Override
686 public void verifyGroups(DeviceId id) {
687 DefaultGroupHandler gh = groupHandlerMap.get(id);
688 if (gh != null) {
689 gh.triggerBucketCorrector();
690 }
691 }
692
Saurav Das6430f412018-01-25 09:49:01 -0800693 @Override
694 public ImmutableMap<Link, Boolean> getSeenLinks() {
695 return linkHandler.getSeenLinks();
696 }
697
698 @Override
699 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
700 return linkHandler.getDownedPorts();
701 }
702
Pier Luigi0f9635b2018-01-15 18:06:43 +0100703 @Override
704 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
705 return mcastHandler.getMcastNextIds(mcastIp);
706 }
707
708 @Override
709 public Map<McastStoreKey, McastHandler.McastRole> getMcastRoles(IpAddress mcastIp) {
710 return mcastHandler.getMcastRoles(mcastIp);
711 }
712
713 @Override
714 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
715 return mcastHandler.getMcastPaths(mcastIp);
716 }
717
sangho80f1f892015-05-19 11:57:42 -0700718 /**
Ray Milkeyb85de082017-04-05 09:42:04 -0700719 * Extracts the application ID from the manager.
720 *
721 * @return application ID
722 */
723 public ApplicationId appId() {
724 return appId;
725 }
726
727 /**
728 * Returns the device configuration.
729 *
730 * @return device configuration
731 */
732 public DeviceConfiguration deviceConfiguration() {
733 return deviceConfiguration;
734 }
735
736 /**
Saurav Das261c3002017-06-13 15:35:54 -0700737 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700738 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700739 *
740 * @return next objective ID store
741 */
Saurav Das261c3002017-06-13 15:35:54 -0700742 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
743 dsNextObjStore() {
744 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700745 }
746
747 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700748 * Per device next objective ID store with (device id + vlanid) as key.
749 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700750 *
751 * @return vlan next object store
752 */
753 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
754 return vlanNextObjStore;
755 }
756
757 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700758 * Per device next objective ID store with (device id + port + treatment + meta) as key.
759 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700760 *
761 * @return port next object store.
762 */
763 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
764 return portNextObjStore;
765 }
766
767 /**
Saurav Das261c3002017-06-13 15:35:54 -0700768 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
769 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700770 *
771 * @return MPLS-ECMP value
772 */
773 public boolean getMplsEcmp() {
774 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
775 .getConfig(this.appId, SegmentRoutingAppConfig.class);
776 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
777 }
778
779 /**
sangho80f1f892015-05-19 11:57:42 -0700780 * Returns the tunnel object with the tunnel ID.
781 *
782 * @param tunnelId Tunnel ID
783 * @return Tunnel reference
784 */
sangho27462c62015-05-14 00:39:53 -0700785 public Tunnel getTunnel(String tunnelId) {
786 return tunnelHandler.getTunnel(tunnelId);
787 }
788
Charles Chan90772a72017-02-08 15:52:08 -0800789 // TODO Consider moving these to InterfaceService
sangho80f11cb2015-04-01 13:05:26 -0700790 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800791 * Returns untagged VLAN configured on given connect point.
Charles Chan90772a72017-02-08 15:52:08 -0800792 * <p>
793 * Only returns the first match if there are multiple untagged VLAN configured
794 * on the connect point.
sangho80f11cb2015-04-01 13:05:26 -0700795 *
Charles Chan10b0fb72017-02-02 16:20:42 -0800796 * @param connectPoint connect point
797 * @return untagged VLAN or null if not configured
sangho80f11cb2015-04-01 13:05:26 -0700798 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700799 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800800 return interfaceService.getInterfacesByPort(connectPoint).stream()
801 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
802 .map(Interface::vlanUntagged)
803 .findFirst().orElse(null);
sangho80f11cb2015-04-01 13:05:26 -0700804 }
805
sangho27462c62015-05-14 00:39:53 -0700806 /**
Charles Chan90772a72017-02-08 15:52:08 -0800807 * Returns tagged VLAN configured on given connect point.
808 * <p>
809 * Returns all matches if there are multiple tagged VLAN configured
810 * on the connect point.
811 *
812 * @param connectPoint connect point
813 * @return tagged VLAN or empty set if not configured
814 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700815 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800816 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
817 return interfaces.stream()
818 .map(Interface::vlanTagged)
Charles Chan3ed34d82017-06-22 18:03:14 -0700819 .flatMap(Set::stream)
Charles Chan90772a72017-02-08 15:52:08 -0800820 .collect(Collectors.toSet());
821 }
822
823 /**
824 * Returns native VLAN configured on given connect point.
825 * <p>
826 * Only returns the first match if there are multiple native VLAN configured
827 * on the connect point.
828 *
829 * @param connectPoint connect point
830 * @return native VLAN or null if not configured
831 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700832 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800833 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
834 return interfaces.stream()
835 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
836 .map(Interface::vlanNative)
837 .findFirst()
838 .orElse(null);
839 }
840
841 /**
Charles Chand9265a32017-06-16 15:19:24 -0700842 * Returns internal VLAN for untagged hosts on given connect point.
843 * <p>
844 * The internal VLAN is either vlan-untagged for an access port,
845 * or vlan-native for a trunk port.
846 *
847 * @param connectPoint connect point
848 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
849 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700850 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chand9265a32017-06-16 15:19:24 -0700851 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
852 VlanId nativeVlanId = getNativeVlanId(connectPoint);
853 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
854 }
855
856 /**
Charles Chan3ed34d82017-06-22 18:03:14 -0700857 * Returns optional pair device ID of given device.
858 *
859 * @param deviceId device ID
860 * @return optional pair device ID. Might be empty if pair device is not configured
861 */
862 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
863 SegmentRoutingDeviceConfig deviceConfig =
864 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
865 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
866 }
867 /**
868 * Returns optional pair device local port of given device.
869 *
870 * @param deviceId device ID
871 * @return optional pair device ID. Might be empty if pair device is not configured
872 */
873 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
874 SegmentRoutingDeviceConfig deviceConfig =
875 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
876 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
877 }
878
879 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700880 * Determine if current instance is the master of given connect point.
881 *
882 * @param cp connect point
883 * @return true if current instance is the master of given connect point
884 */
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700885 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan910be6a2017-08-23 14:46:43 -0700886 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
887 if (!isMaster) {
888 log.debug(NOT_MASTER, cp);
889 }
890 return isMaster;
891 }
892
893 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700894 * Returns locations of given resolved route.
895 *
896 * @param resolvedRoute resolved route
897 * @return locations of nexthop. Might be empty if next hop is not found
898 */
899 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
900 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
901 return Optional.ofNullable(hostService.getHost(hostId))
902 .map(Host::locations).orElse(Sets.newHashSet())
903 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
904 }
905
906 /**
Charles Chan90772a72017-02-08 15:52:08 -0800907 * Returns vlan port map of given device.
908 *
909 * @param deviceId device id
910 * @return vlan-port multimap
911 */
912 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
913 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
914
915 interfaceService.getInterfaces().stream()
916 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
917 .forEach(intf -> {
918 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700919 intf.vlanTagged().forEach(vlanTagged ->
920 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
921 );
Charles Chan90772a72017-02-08 15:52:08 -0800922 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
923 });
924 vlanPortMap.removeAll(VlanId.NONE);
925
926 return vlanPortMap;
927 }
928
929 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800930 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800931 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700932 *
933 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800934 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800935 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700936 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700937 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700938 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800939 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
940 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700941 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800942 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800943 + "device {} not found", deviceId);
944 return -1;
945 }
946 }
947
948 /**
949 * Returns the next objective ID for the given portNumber, given the treatment.
950 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700951 * would result in different objectives. If the next object does not exist,
952 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800953 *
954 * @param deviceId Device ID
955 * @param portNum port number on device for which NextObjective is queried
956 * @param treatment the actions to apply on the packets (should include outport)
957 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700958 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700959 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800960 */
961 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
962 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700963 TrafficSelector meta,
964 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800965 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
966 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700967 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800968 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800969 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
970 + " not found", deviceId);
971 return -1;
972 }
973 }
974
Saurav Das62ae6792017-05-15 15:34:25 -0700975 /**
976 * Returns the group handler object for the specified device id.
977 *
978 * @param devId the device identifier
979 * @return the groupHandler object for the device id, or null if not found
980 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700981 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -0700982 return groupHandlerMap.get(devId);
983 }
984
985 /**
Saurav Dasfbe74572017-08-03 18:30:35 -0700986 * Returns the default routing handler object.
987 *
988 * @return the default routing handler object
989 */
990 public DefaultRoutingHandler getRoutingHandler() {
991 return defaultRoutingHandler;
992 }
993
sangho80f11cb2015-04-01 13:05:26 -0700994 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -0700995 @Override
996 public void process(PacketContext context) {
997
998 if (context.isHandled()) {
999 return;
1000 }
1001
1002 InboundPacket pkt = context.inPacket();
1003 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001004
1005 if (ethernet == null) {
1006 return;
1007 }
1008
Saurav Das261c3002017-06-13 15:35:54 -07001009 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1010 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001011 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001012 log.warn("Received unexpected ARP packet on {}",
1013 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001014 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001015 return;
sangho80f11cb2015-04-01 13:05:26 -07001016 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001017 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1018 //ipHandler.addToPacketBuffer(ipv4Packet);
1019 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1020 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001021 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001022 // NOTE: We don't support IP learning at this moment so this
1023 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001024 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001025 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001026 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1027 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001028 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001029 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001030 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1031 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1032 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1033 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1034 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1035 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001036 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001037 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001038 }
1039 } else {
1040 // NOTE: We don't support IP learning at this moment so this
1041 // is not necessary. Also it causes duplication of DHCPv6 packets.
1042 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1043 }
sangho80f11cb2015-04-01 13:05:26 -07001044 }
1045 }
1046 }
1047
1048 private class InternalLinkListener implements LinkListener {
1049 @Override
1050 public void event(LinkEvent event) {
Charles Chan0cff8aa2017-03-29 16:39:05 -07001051 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1052 event.type() == LinkEvent.Type.LINK_UPDATED ||
1053 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001054 log.debug("Event {} received from Link Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001055 scheduleEventHandlerIfNotScheduled(event);
1056 }
1057 }
1058 }
1059
1060 private class InternalDeviceListener implements DeviceListener {
sangho80f11cb2015-04-01 13:05:26 -07001061 @Override
1062 public void event(DeviceEvent event) {
sangho80f11cb2015-04-01 13:05:26 -07001063 switch (event.type()) {
1064 case DEVICE_ADDED:
Saurav Dasf0f592d2016-11-18 15:21:57 -08001065 case PORT_UPDATED:
1066 case PORT_ADDED:
sanghofb7c7292015-04-13 15:15:58 -07001067 case DEVICE_UPDATED:
1068 case DEVICE_AVAILABILITY_CHANGED:
Saurav Das62ae6792017-05-15 15:34:25 -07001069 log.trace("Event {} received from Device Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001070 scheduleEventHandlerIfNotScheduled(event);
1071 break;
1072 default:
1073 }
1074 }
1075 }
1076
Pier Luigid8a15162018-02-15 16:33:08 +01001077 /**
1078 * Internal listener for topology events.
1079 */
1080 private class InternalTopologyListener implements TopologyListener {
1081 @Override
1082 public void event(TopologyEvent event) {
1083 switch (event.type()) {
1084 case TOPOLOGY_CHANGED:
1085 log.debug("Event {} received from TopologyService", event.type());
1086 scheduleEventHandlerIfNotScheduled(event);
1087 break;
1088 default:
1089 }
1090 }
1091 }
1092
Saurav Das2d94d312015-11-24 23:21:05 -08001093 @SuppressWarnings("rawtypes")
sangho80f11cb2015-04-01 13:05:26 -07001094 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001095 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001096 eventQueue.add(event);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001097 numOfEventsQueued++;
1098
1099 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1100 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001101 eventHandlerFuture = executorService
1102 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1103 numOfHandlerScheduled++;
1104 }
Jonathan Hart54541d12016-04-12 15:39:44 -07001105 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001106 numOfEventsQueued,
1107 numOfHandlerScheduled);
sangho80f11cb2015-04-01 13:05:26 -07001108 }
sangho80f11cb2015-04-01 13:05:26 -07001109 }
1110
1111 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001112 @Override
sangho80f11cb2015-04-01 13:05:26 -07001113 public void run() {
Pier Luigi8f362362018-02-12 09:56:20 +01001114 while (true) {
1115 try {
Saurav Das2d94d312015-11-24 23:21:05 -08001116 @SuppressWarnings("rawtypes")
Charles Chan3ed34d82017-06-22 18:03:14 -07001117 Event event;
1118 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001119 if (!eventQueue.isEmpty()) {
1120 event = eventQueue.poll();
1121 numOfEventsExecuted++;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001122 } else {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001123 numOfHandlerExecution++;
1124 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1125 numOfHandlerExecution, numOfEventsExecuted);
1126 break;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001127 }
sanghofb7c7292015-04-13 15:15:58 -07001128 }
Pier Luigid8a15162018-02-15 16:33:08 +01001129 // TODO We should also change SR routing and PW to listen to TopologyEvents
Charles Chan0cff8aa2017-03-29 16:39:05 -07001130 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1131 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Dase6c448a2018-01-18 12:07:33 -08001132 linkHandler.processLinkAdded((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001133 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Saurav Dase6c448a2018-01-18 12:07:33 -08001134 linkHandler.processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001135 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1136 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1137 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das62af8802015-12-04 10:52:59 -08001138 DeviceId deviceId = ((Device) event.subject()).id();
1139 if (deviceService.isAvailable(deviceId)) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001140 log.info("Processing device event {} for available device {}",
1141 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001142 processDeviceAdded((Device) event.subject());
Saurav Dasc3604f12016-03-23 11:22:49 -07001143 } else {
1144 log.info("Processing device event {} for unavailable device {}",
Pier Luigi8f362362018-02-12 09:56:20 +01001145 event.type(), ((Device) event.subject()).id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001146 processDeviceRemoved((Device) event.subject());
1147 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001148 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001149 // typically these calls come when device is added first time
1150 // so port filtering rules are handled at the device_added event.
1151 // port added calls represent all ports on the device,
1152 // enabled or not.
Saurav Das62ae6792017-05-15 15:34:25 -07001153 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd1872b02016-12-02 15:43:47 -08001154 ((DeviceEvent) event).subject().id(),
1155 ((DeviceEvent) event).port().number(),
1156 event.type());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001157 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001158 // these calls happen for every subsequent event
1159 // ports enabled, disabled, switch goes away, comes back
Saurav Dasf0f592d2016-11-18 15:21:57 -08001160 log.info("** PORT UPDATED {}/{} -> {}",
1161 event.subject(),
1162 ((DeviceEvent) event).port(),
1163 event.type());
1164 processPortUpdated(((Device) event.subject()),
1165 ((DeviceEvent) event).port());
Pier Luigid8a15162018-02-15 16:33:08 +01001166 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1167 // Process topology event, needed for all modules relying on
1168 // topology service for path computation
1169 TopologyEvent topologyEvent = (TopologyEvent) event;
1170 log.info("Processing topology event {}, topology age {}, reasons {}",
1171 event.type(), topologyEvent.subject().time(),
1172 topologyEvent.reasons().size());
1173 topologyHandler.processTopologyChange(topologyEvent.reasons());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001174 } else {
1175 log.warn("Unhandled event type: {}", event.type());
1176 }
Pier Luigi8f362362018-02-12 09:56:20 +01001177 } catch (Exception e) {
1178 log.error("SegmentRouting event handler thread thrown an exception: {}",
1179 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001180 }
1181 }
sangho80f11cb2015-04-01 13:05:26 -07001182 }
1183 }
1184
Saurav Dase6c448a2018-01-18 12:07:33 -08001185 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001186 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001187
1188 // NOTE: Punt ARP/NDP even when the device is not configured.
1189 // Host learning without network config is required for CORD config generator.
1190 routingRulePopulator.populateIpPunts(device.id());
1191 routingRulePopulator.populateArpNdpPunts(device.id());
1192
Charles Chan319d1a22015-11-03 10:42:14 -08001193 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001194 log.warn("Device configuration unavailable. Device {} will be "
1195 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001196 return;
1197 }
Charles Chan72779502016-04-23 17:36:10 -07001198 processDeviceAddedInternal(device.id());
1199 }
1200
1201 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001202 // Irrespective of whether the local is a MASTER or not for this device,
1203 // we need to create a SR-group-handler instance. This is because in a
1204 // multi-instance setup, any instance can initiate forwarding/next-objectives
1205 // for any switch (even if this instance is a SLAVE or not even connected
1206 // to the switch). To handle this, a default-group-handler instance is necessary
1207 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001208 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1209 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001210 DefaultGroupHandler groupHandler;
1211 try {
1212 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001213 createGroupHandler(deviceId,
1214 appId,
1215 deviceConfiguration,
1216 linkService,
1217 flowObjectiveService,
1218 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001219 } catch (DeviceConfigNotFoundException e) {
1220 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1221 return;
1222 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001223 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001224 deviceId);
1225 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001226 }
Saurav Dasb149be12016-06-07 10:08:06 -07001227
Charles Chan72779502016-04-23 17:36:10 -07001228 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001229 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chandebfea32016-10-24 14:52:01 -07001230 hostHandler.init(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001231 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001232 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001233 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001234 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001235 }
Charles Chan82ab1932016-01-30 23:22:37 -08001236
Charles Chandebfea32016-10-24 14:52:01 -07001237 appCfgHandler.init(deviceId);
1238 routeHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001239 }
1240
Saurav Dasc3604f12016-03-23 11:22:49 -07001241 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001242 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001243 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001244 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001245 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001246 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001247 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001248 portNextObjStore.entrySet().stream()
1249 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001250 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001251 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001252
Saurav Dasfbe74572017-08-03 18:30:35 -07001253 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1254 if (gh != null) {
1255 gh.shutdown();
1256 }
Saurav Das62ae6792017-05-15 15:34:25 -07001257 // Note that a switch going down is associated with all of its links
1258 // going down as well, but it is treated as a single switch down event
1259 // while the link-downs are ignored.
1260 defaultRoutingHandler
1261 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Saurav Das6430f412018-01-25 09:49:01 -08001262 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001263 xConnectHandler.removeDevice(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001264 }
1265
Saurav Dasf0f592d2016-11-18 15:21:57 -08001266 private void processPortUpdated(Device device, Port port) {
1267 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1268 log.warn("Device configuration uploading. Not handling port event for"
1269 + "dev: {} port: {}", device.id(), port.number());
1270 return;
1271 }
Saurav Dasf9332192017-02-18 14:05:44 -08001272
1273 if (!mastershipService.isLocalMaster(device.id())) {
1274 log.debug("Not master for dev:{} .. not handling port updated event"
1275 + "for port {}", device.id(), port.number());
1276 return;
1277 }
1278
1279 // first we handle filtering rules associated with the port
1280 if (port.isEnabled()) {
1281 log.info("Switchport {}/{} enabled..programming filters",
1282 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001283 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001284 } else {
1285 log.info("Switchport {}/{} disabled..removing filters",
1286 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001287 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001288 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001289
1290 // portUpdated calls are for ports that have gone down or up. For switch
1291 // to switch ports, link-events should take care of any re-routing or
1292 // group editing necessary for port up/down. Here we only process edge ports
1293 // that are already configured.
Saurav Das3fb28272017-03-04 16:08:47 -08001294 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1295 VlanId untaggedVlan = getUntaggedVlanId(cp);
1296 VlanId nativeVlan = getNativeVlanId(cp);
1297 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001298
Saurav Das3fb28272017-03-04 16:08:47 -08001299 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001300 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001301 + "dev/port: {}/{}", device.id(), port.number());
1302 return;
1303 }
Saurav Das3fb28272017-03-04 16:08:47 -08001304 if (untaggedVlan != null) {
1305 processEdgePort(device, port, untaggedVlan, true);
1306 }
1307 if (nativeVlan != null) {
1308 processEdgePort(device, port, nativeVlan, true);
1309 }
1310 if (!taggedVlans.isEmpty()) {
1311 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1312 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001313 }
1314
Saurav Das3fb28272017-03-04 16:08:47 -08001315 private void processEdgePort(Device device, Port port, VlanId vlanId,
1316 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001317 boolean portUp = port.isEnabled();
1318 if (portUp) {
Saurav Das3fb28272017-03-04 16:08:47 -08001319 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001320 port.number(), vlanId);
Charles Chan873661e2017-11-30 15:37:50 -08001321 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001322 } else {
Saurav Das3fb28272017-03-04 16:08:47 -08001323 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001324 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001325 }
1326
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001327 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sangho80f11cb2015-04-01 13:05:26 -07001328 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001329 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001330 } else {
1331 log.warn("Group handler not found for dev:{}. Not handling edge port"
1332 + " {} event for port:{}", device.id(),
1333 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001334 }
1335 }
sangho27462c62015-05-14 00:39:53 -07001336
Charles Chan8ca5a122017-10-20 16:06:55 -07001337 private void createOrUpdateDeviceConfiguration() {
1338 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001339 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001340 deviceConfiguration = new DeviceConfiguration(this);
1341 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001342 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001343 deviceConfiguration.updateConfig();
1344 }
1345 }
1346
Pier Ventreb6a7f342016-11-26 21:05:22 -08001347 /**
1348 * Registers the given connect point with the NRS, this is necessary
1349 * to receive the NDP and ARP packets from the NRS.
1350 *
1351 * @param portToRegister connect point to register
1352 */
1353 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001354 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001355 portToRegister,
1356 neighbourHandler,
1357 appId
1358 );
1359 }
1360
Charles Chan72f556a2015-10-05 17:50:33 -07001361 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001362 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001363 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001364
Charles Chanb7f75ac2016-01-11 18:28:54 -08001365 /**
1366 * Constructs the internal network config listener.
1367 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001368 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001369 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001370 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001371 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001372 }
1373
Charles Chanb7f75ac2016-01-11 18:28:54 -08001374 /**
1375 * Reads network config and initializes related data structure accordingly.
1376 */
Charles Chan873661e2017-11-30 15:37:50 -08001377 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001378 log.info("Configuring network ...");
Charles Chan8ca5a122017-10-20 16:06:55 -07001379 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001380
Charles Chan46fdfaf2016-11-09 20:51:44 -08001381 arpHandler = new ArpHandler(srManager);
1382 icmpHandler = new IcmpHandler(srManager);
1383 ipHandler = new IpHandler(srManager);
1384 routingRulePopulator = new RoutingRulePopulator(srManager);
1385 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chane7c61022015-10-07 14:21:45 -07001386
1387 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1388 groupHandlerMap, tunnelStore);
1389 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1390 flowObjectiveService,
1391 tunnelHandler, policyStore);
Saurav Das261c3002017-06-13 15:35:54 -07001392 // add a small delay to absorb multiple network config added notifications
1393 if (!programmingScheduled.get()) {
Saurav Dase321cff2018-02-09 17:26:45 -08001394 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das261c3002017-06-13 15:35:54 -07001395 programmingScheduled.set(true);
1396 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1397 TimeUnit.SECONDS);
Charles Chane7c61022015-10-07 14:21:45 -07001398 }
Charles Chan72779502016-04-23 17:36:10 -07001399 mcastHandler.init();
Charles Chane7c61022015-10-07 14:21:45 -07001400 }
1401
Charles Chan72f556a2015-10-05 17:50:33 -07001402 @Override
1403 public void event(NetworkConfigEvent event) {
Charles Chan82ab1932016-01-30 23:22:37 -08001404 // TODO move this part to NetworkConfigEventHandler
1405 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1406 switch (event.type()) {
1407 case CONFIG_ADDED:
Charles Chan68363b12017-06-26 15:25:09 -07001408 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan82ab1932016-01-30 23:22:37 -08001409 configureNetwork();
1410 break;
1411 case CONFIG_UPDATED:
Charles Chan68363b12017-06-26 15:25:09 -07001412 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001413 createOrUpdateDeviceConfiguration();
Charles Chan68363b12017-06-26 15:25:09 -07001414 // TODO support dynamic configuration
1415 break;
1416 default:
1417 break;
1418 }
1419 } else if (event.configClass().equals(InterfaceConfig.class)) {
1420 switch (event.type()) {
1421 case CONFIG_ADDED:
1422 log.info("Interface Config added for {}", event.subject());
1423 configureNetwork();
1424 break;
1425 case CONFIG_UPDATED:
1426 log.info("Interface Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001427 createOrUpdateDeviceConfiguration();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001428
1429 // Following code will be uncommented when [CORD-634] is fully implemented.
1430 // [CORD-634] Add dynamic config support for interfaces
1431 updateInterface((InterfaceConfig) event.config().get(),
1432 (InterfaceConfig) event.prevConfig().get());
Charles Chan82ab1932016-01-30 23:22:37 -08001433 // TODO support dynamic configuration
1434 break;
1435 default:
1436 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001437 }
Charles Chan82ab1932016-01-30 23:22:37 -08001438 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chan82f19972016-05-17 13:13:55 -07001439 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan82ab1932016-01-30 23:22:37 -08001440 switch (event.type()) {
1441 case CONFIG_ADDED:
Charles Chan82f19972016-05-17 13:13:55 -07001442 appCfgHandler.processAppConfigAdded(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001443 break;
1444 case CONFIG_UPDATED:
Charles Chan82f19972016-05-17 13:13:55 -07001445 appCfgHandler.processAppConfigUpdated(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001446 break;
1447 case CONFIG_REMOVED:
Charles Chan82f19972016-05-17 13:13:55 -07001448 appCfgHandler.processAppConfigRemoved(event);
1449 break;
1450 default:
1451 break;
1452 }
Saurav Dase321cff2018-02-09 17:26:45 -08001453 log.info("App config event .. configuring network");
Charles Chandebfea32016-10-24 14:52:01 -07001454 configureNetwork();
Charles Chan82f19972016-05-17 13:13:55 -07001455 } else if (event.configClass().equals(XConnectConfig.class)) {
1456 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1457 switch (event.type()) {
1458 case CONFIG_ADDED:
1459 xConnectHandler.processXConnectConfigAdded(event);
1460 break;
1461 case CONFIG_UPDATED:
1462 xConnectHandler.processXConnectConfigUpdated(event);
1463 break;
1464 case CONFIG_REMOVED:
1465 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001466 break;
1467 default:
1468 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001469 }
Charles Chan72f556a2015-10-05 17:50:33 -07001470 }
1471 }
Saurav Das261c3002017-06-13 15:35:54 -07001472
Charles Chanc4a68c32018-01-03 16:26:32 -08001473 @Override
1474 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001475 if (event.type() == CONFIG_REGISTERED ||
1476 event.type() == CONFIG_UNREGISTERED) {
1477 log.debug("Ignore event {} due to type mismatch", event);
1478 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001479 }
Saurav Dase321cff2018-02-09 17:26:45 -08001480
1481 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1482 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1483 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -08001484 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001485 log.debug("Ignore event {} due to class mismatch", event);
1486 return false;
1487 }
1488
1489 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001490 }
1491
Saurav Das261c3002017-06-13 15:35:54 -07001492 private final class ConfigChange implements Runnable {
1493 @Override
1494 public void run() {
1495 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001496 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001497 for (Device device : deviceService.getDevices()) {
1498 processDeviceAdded(device);
1499 }
1500 defaultRoutingHandler.startPopulationProcess();
1501 }
1502 }
Charles Chan72f556a2015-10-05 17:50:33 -07001503 }
Charles Chanf4586112015-11-09 16:37:23 -08001504
1505 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001506 @Override
1507 public void event(HostEvent event) {
Charles Chanf4586112015-11-09 16:37:23 -08001508 switch (event.type()) {
1509 case HOST_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001510 hostHandler.processHostAddedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001511 break;
1512 case HOST_MOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001513 hostHandler.processHostMovedEvent(event);
Charles Chan910be6a2017-08-23 14:46:43 -07001514 routeHandler.processHostMovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001515 break;
1516 case HOST_REMOVED:
Charles Chand9265a32017-06-16 15:19:24 -07001517 hostHandler.processHostRemovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001518 break;
1519 case HOST_UPDATED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001520 hostHandler.processHostUpdatedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001521 break;
1522 default:
1523 log.warn("Unsupported host event type: {}", event.type());
1524 break;
1525 }
1526 }
1527 }
1528
Charles Chanc91c8782016-03-30 17:54:24 -07001529 private class InternalMcastListener implements McastListener {
1530 @Override
1531 public void event(McastEvent event) {
1532 switch (event.type()) {
1533 case SOURCE_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001534 mcastHandler.processSourceAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001535 break;
1536 case SINK_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001537 mcastHandler.processSinkAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001538 break;
1539 case SINK_REMOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001540 mcastHandler.processSinkRemoved(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001541 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001542 case ROUTE_REMOVED:
Pier Luigi6786b922018-02-02 16:19:11 +01001543 mcastHandler.processRouteRemoved(event);
1544 break;
1545 case ROUTE_ADDED:
Charles Chanc91c8782016-03-30 17:54:24 -07001546 default:
1547 break;
1548 }
1549 }
1550 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001551
Charles Chandebfea32016-10-24 14:52:01 -07001552 private class InternalRouteEventListener implements RouteListener {
1553 @Override
1554 public void event(RouteEvent event) {
1555 switch (event.type()) {
1556 case ROUTE_ADDED:
1557 routeHandler.processRouteAdded(event);
1558 break;
1559 case ROUTE_UPDATED:
1560 routeHandler.processRouteUpdated(event);
1561 break;
1562 case ROUTE_REMOVED:
1563 routeHandler.processRouteRemoved(event);
1564 break;
Charles Chan910be6a2017-08-23 14:46:43 -07001565 case ALTERNATIVE_ROUTES_CHANGED:
1566 routeHandler.processAlternativeRoutesChanged(event);
1567 break;
Charles Chandebfea32016-10-24 14:52:01 -07001568 default:
1569 break;
1570 }
1571 }
1572 }
Saurav Das62ae6792017-05-15 15:34:25 -07001573
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001574 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1575 try {
1576 Set<Interface> intfs = conf.getInterfaces();
1577 Set<Interface> prevIntfs = prevConf.getInterfaces();
1578
1579 // Now we only handle one interface config at each port.
1580 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1581 log.warn("Interface update aborted - one at a time is allowed, " +
1582 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1583 return;
1584 }
1585
1586 Interface intf = intfs.stream().findFirst().get();
1587 Interface prevIntf = prevIntfs.stream().findFirst().get();
1588
1589 DeviceId deviceId = intf.connectPoint().deviceId();
1590 PortNumber portNum = intf.connectPoint().port();
1591
1592 if (!mastershipService.isLocalMaster(deviceId)) {
1593 log.debug("CONFIG_UPDATED event for interfaces should be " +
1594 "handled by master node for device {}", deviceId);
1595 return;
1596 }
1597
1598 removeSubnetConfig(prevIntf.connectPoint(),
1599 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1600 new HashSet<>(intf.ipAddressesList())));
1601
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001602 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1603 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1604 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1605 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1606 // Update filtering objective and L2IG group bucket
1607 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1608 } else {
1609 // RemoveVlanNative
1610 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1611 }
1612 }
1613
1614 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1615 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1616 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1617 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1618 // Update filtering objective and L2IG group bucket
1619 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1620 } else {
1621 // RemoveVlanUntagged
1622 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1623 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001624 }
1625
1626 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1627 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001628 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1629 .filter(i -> !intf.vlanUntagged().equals(i))
1630 .filter(i -> !intf.vlanNative().equals(i))
1631 .forEach(vlanId -> updateVlanConfigInternal(
1632 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001633 }
1634
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001635 if (!intf.vlanNative().equals(VlanId.NONE)
1636 && !prevIntf.vlanNative().equals(intf.vlanNative())
1637 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1638 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1639 // Update filtering objective and L2IG group bucket
1640 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1641 } else {
1642 // AddVlanNative
1643 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1644 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001645 }
1646
1647 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1648 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001649 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1650 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1651 .filter(i -> !prevIntf.vlanNative().equals(i))
1652 .forEach(vlanId -> updateVlanConfigInternal(
1653 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001654 );
1655 }
1656
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001657 if (!intf.vlanUntagged().equals(VlanId.NONE)
1658 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1659 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1660 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1661 // Update filtering objective and L2IG group bucket
1662 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1663 } else {
1664 // AddVlanUntagged
1665 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1666 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001667 }
1668 addSubnetConfig(prevIntf.connectPoint(),
1669 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1670 new HashSet<>(prevIntf.ipAddressesList())));
1671 } catch (ConfigException e) {
1672 log.error("Error in configuration");
1673 }
1674 }
1675
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001676 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1677 VlanId vlanId, boolean pushVlan) {
1678 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1679 if (grpHandler == null) {
1680 log.warn("Failed to retrieve group handler for device {}", deviceId);
1681 return;
1682 }
1683
1684 // Update filtering objective for a single port
1685 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1686 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1687
1688 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1689 // Update L2IG bucket of the port
1690 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1691 } else {
1692 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1693 }
1694 }
1695
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001696 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1697 VlanId vlanId, boolean pushVlan, boolean install) {
1698 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1699 if (grpHandler == null) {
1700 log.warn("Failed to retrieve group handler for device {}", deviceId);
1701 return;
1702 }
1703
1704 // Update filtering objective for a single port
1705 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1706
1707 // Update filtering objective for multicast ingress port
1708 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1709
1710 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1711
1712 if (nextId != -1 && !install) {
1713 // Update next objective for a single port as an output port
1714 // Remove a single port from L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001715 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001716 // Remove L2 Bridging rule and L3 Unicast rule to the host
1717 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1718 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1719 // only if there is no port configured on that VLAN ID
1720 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1721 // Remove broadcast forwarding rule for the VLAN
1722 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1723 // Remove L2FG for VLAN
1724 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1725 } else {
1726 // Remove L2IG of the port
1727 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1728 }
1729 } else if (install) {
1730 if (nextId != -1) {
1731 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001732 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001733 } else {
1734 // Create L2FG for VLAN
1735 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1736 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1737 }
1738 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1739 } else {
1740 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1741 }
1742 }
1743
1744 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1745 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1746 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1747
1748 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1749 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1750 .filter(intf -> !intf.connectPoint().equals(cp))
1751 .flatMap(intf -> intf.ipAddressesList().stream())
1752 .collect(Collectors.toSet());
1753 // 1. Partial subnet population
1754 // Remove routing rules for removed subnet from previous configuration,
1755 // which does not also exist in other interfaces in the same device
1756 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1757 .map(InterfaceIpAddress::subnetAddress)
1758 .collect(Collectors.toSet());
1759
1760 defaultRoutingHandler.revokeSubnet(
1761 ipPrefixSet.stream()
1762 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1763 .collect(Collectors.toSet()));
1764
1765 // 2. Interface IP punts
1766 // Remove IP punts for old Intf address
1767 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1768 .map(InterfaceIpAddress::ipAddress)
1769 .collect(Collectors.toSet());
1770 ipAddressSet.stream()
1771 .map(InterfaceIpAddress::ipAddress)
1772 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1773 .forEach(interfaceIpAddress ->
1774 routingRulePopulator.revokeSingleIpPunts(
1775 cp.deviceId(), interfaceIpAddress));
1776
1777 // 3. Host unicast routing rule
1778 // Remove unicast routing rule
1779 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1780 }
1781
1782 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1783 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1784 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1785
1786 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1787 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1788 .filter(intf -> !intf.connectPoint().equals(cp))
1789 .flatMap(intf -> intf.ipAddressesList().stream())
1790 .collect(Collectors.toSet());
1791 // 1. Partial subnet population
1792 // Add routing rules for newly added subnet, which does not also exist in
1793 // other interfaces in the same device
1794 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1795 .map(InterfaceIpAddress::subnetAddress)
1796 .collect(Collectors.toSet());
1797
1798 defaultRoutingHandler.populateSubnet(
1799 Collections.singleton(cp),
1800 ipPrefixSet.stream()
1801 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1802 .collect(Collectors.toSet()));
1803
1804 // 2. Interface IP punts
1805 // Add IP punts for new Intf address
1806 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1807 .map(InterfaceIpAddress::ipAddress)
1808 .collect(Collectors.toSet());
1809 ipAddressSet.stream()
1810 .map(InterfaceIpAddress::ipAddress)
1811 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1812 .forEach(interfaceIpAddress ->
1813 routingRulePopulator.populateSingleIpPunts(
1814 cp.deviceId(), interfaceIpAddress));
1815
1816 // 3. Host unicast routing rule
1817 // Add unicast routing rule
1818 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1819 }
sangho80f11cb2015-04-01 13:05:26 -07001820}